之前有人問到野指針的問題,所以最近在查block的相關文章
但查了半天,沒幾個靠譜的文章
于是準備,整理下block相關的,也方便是以后查找起來方便
1.先測試一下
這里有5道測試題(http://blog.parse.com/learn/engineering/objective-c-blocks-quiz/),
屏幕快照 2016-04-15 上午12.41.52.png
如果你都能回答正確,那么,ok,請回吧.
哥們,你真的很棒了!
2.簡單介紹一下block
int main(int argc, const char * argv[]) {
@autoreleasepool {
^{ };
}
return 0;
}
一句話:block 實際上就是 Objective-C 語言對于閉包的實現
3. 業內好文章整理
3.1
談Objective-C block的實現 -- 唐巧
(http://blog.devtang.com/2013/07/28/a-look-inside-blocks/)
對Objective-C中Block的追探
(http://www.cnblogs.com/biosli/archive/2013/05/29/iOS_Objective-C_Block.html)
3.2
Block編程值得注意的那些事兒 (使用相關)
(http://www.cocoachina.com/macdev/cocoa/2013/0527/6285.html)
iOS中block實現的探究(內部結構分析)
(http://blog.csdn.net/jasonblog/article/details/7756763?reload)
又看了一本關于這方面的書:
Pro Multithreading and Memory Management for iOS and OS X
(http://vdisk.weibo.com/s/9hjAV)
4 補充
4.1 循環引用與野指針
- block避免循環引用的方法是使用 __weak, 當然,這個是針對這個block本身就是self的成員
- 使用__weak之后,會引發新的問題,就是可能會帶來野指針,因為weak是在arc里面引用后直接置為nil的,所以為了避免野指針的問題,還需要一個__strong
"野指針"不是NULL指針,是指向"垃圾"內存(不可用內存)的指針。野指針是非常危險的。
- 綜上,以上的代碼應該是:
__weak __typeof__(self) weakSelf = self;
dispatch_group_async(_operationsGroup, _operationsQueue, ^{
__typeof__(self) strongSelf = weakSelf;
[strongSelf doSomething];
[strongSelf doSomethingElse];
} );
- 代碼里如果使用->調用成員變量,會出現問題:
Dereferencing a __weak pointer is not allowed due to possible null value caused by race condition, assign it to a strong variable first.
__weak pointer
解決方案:
a. 換成block
__block typeof(self) weakSelf = self;
[popView setOnButtonTouchUpInside:^(CustomIOS7AlertView *alertView, int buttonIndex){
[weakSelf->popView close];
}];
b. 使用strongSelf
__weak typeof(self) weakSelf = self;
[popView setOnButtonTouchUpInside:^(CustomIOS7AlertView* alertView, int buttonIndex) {
__typeof__(self) strongSelf = weakSelf;
[strongSelf->popView close];
}];