我在ReactiveCocoa和libextobjc中找到了这种用法。我知道,当编译@strongify时,它已改为:
@try {} @finally {}
__attribute__((objc_ownership(strong))) __typeof__(self) self = self_weak_;
当块被执行时,它将创建一个名为self的局部变量并替换全局变量。
@interface A: NSObject
@property (nonatomic,copy) TestBlock testBlock;
@end
@implementation A
- (void) someAPI{
@weakify(self)
self.testBlock = ^{
@strongify(self)//the global variable of self was captured by this block before this line was executed.
if (self != nil)
{
[self doSomethingAwesome];
[self doSomethingAwesomeAgain];
}
};
}
@end
我的问题: 1.是否在执行块之前生成了局部变量。 2.如果块被复制并且从未被调用过,那么它会生成保留圆吗?
抱歉我的英语不好!
答案 0 :(得分:0)
@weakify和@strongify是宏。在编译代码之前,宏在预处理期间会扩展。展开宏时,很明显这里没有保留周期。
- (void) someAPI{
__weak A *self_weak_ = self;
self.testBlock = ^{
//suppress shadowing variable warning
_Pragma("clang diagnostic push")
_Pragma("clang diagnostic ignored \"-Wshadow\"")
__strong A *self = self_weak_; //this is a new reference, the original self is not being captured.
//pop shadowing variable warning
_Pragma("clang diagnostic pop")
if (self != nil)
{
[self doSomethingAwesome];
[self doSomethingAwesomeAgain];
}
};
}