在学习AFNetWorking的过程中,经常看到类似:
//__weak __typeof(self)weakSelf = self;
//然后在block中,看到:
//__strong __typeof(weakSelf)strongSelf = weakSelf;
//如下边代码:
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler {
[self.lock lock];
if (!self.backgroundTaskIdentifier) {
UIApplication *application = [UIApplication sharedApplication];
__weak __typeof(self)weakSelf = self;
self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
__strong __typeof(weakSelf)strongSelf = weakSelf;
if (handler) {
handler();
}
if (strongSelf) {
[strongSelf cancel];
[application endBackgroundTask:strongSelf.backgroundTaskIdentifier];
strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}
}];
}
[self.lock unlock];
}
这是因为:没有添加__strong 引用的话,编译器会有警告,为什么会警告呢,因为弱引用的weakself会在某个时间被释放,有可能是在执行之后的block之前就会被释放,这样在后续的操作操作就有可能出错,所以最好是添加一个对weakSelf的__strong引用。
2 http://stackoverflow.com/questions/19018456/ios-blocks-and-strong-weak-references-to-self