使用weakSelf / strongSelf模式来避免在块中创建保留周期,此代码非常常见:
typeof(self) __weak weakSelf = self; void (^block)() = ^{ typeof(weakSelf) strongSelf = weakSelf; // ...more code... };
问题是,将第二种类型(weakSelf)更改为typeof(self)会导致在块中捕获self吗?
例如:
typeof(self) __weak weakSelf = self; void (^block)() = ^{ typeof(self) strongSelf = weakSelf; // does using typeof(self) here end up capturing self? // ...more code... };
如果没有捕获自我,是否有任何理由偏爱这种或那种方式?
解决方法
它没有. Ken所说的关于typeof是一个编译时表达式确实适用.
这里还有一段代码证明了这一点:
#import <Foundation/Foundation.h> int main(int argc,char *argv[]) { @autoreleasepool { NSObject *o = [NSObject new]; __weak typeof(o) weakO = o; void(^b)() = ^{ __strong typeof(o) strongO = weakO; NSLog(@"o: %@",strongO); }; o = nil; b(); /* outputs: 2015-05-15 16:52:09.225 Untitled[28092:2051417] o: (null) */ } }