探究方法:利用clang把oc实现转成cpp实现:
xcrun -sdk iphonesimulator clang -rewrite-objc -fobjc-arc -stdlib=libc++ -mmacosx-version-min=10.7 -fobjc-runtime=macosx-10.7 -Wno-deprecated-declarations -F /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/System/Library/Frameworks main.m
翻译前后源码对比:
翻以前:
DEAF2789-EB63-4502-AC8E-9BDCDDE9E7A0.png
翻以后:
B40EF58E-C1CE-493E-AD48-75D5C9ED79D5.png
问题1描述:
问:这样会循环引用吗?
@interface ViewController : UITableViewController
@property (nonatomic, copy) void (^myUniqueTestBlock)(void);
@property (nonatomic, copy) void (^myAnotherUniqueTestBlock)(void);
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
@weakify(self)
self.myUniqueTestBlock = ^(void){
[self.view addSubview:[[UIView alloc] init]];
};
}
@end
答:会,15行给block赋值的时候,会生成一个名为__ViewController__viewDidLoad_block_impl_0的struct作为对这个block的定义,其中一个成员即为:__strong typeof (self) self; 此时,用于初始化这个结构体的构造函数__ViewController__viewDidLoad_block_impl_0的参数也传的是self(不过这不是实质,实质还是定义中就是strong)。至于这个struct是怎么生成的,为什么是__strong typeof (self) self,待我再探究一下,就目前来看,用到谁了,结构体里就会出现同名同类型的变量。
@interface ViewController : UITableViewController
@property (nonatomic, copy) void (^myUniqueTestBlock)(void);
@property (nonatomic, copy) void (^myAnotherUniqueTestBlock)(void);
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
@weakify(self) // 翻译成:__attribute__((objc_ownership(weak))) __typeof__(self) self_weak_ = (self);
self.myUniqueTestBlock = ^(void){ // 此处传给__ViewController__viewDidLoad_block_impl_0(block结构体构造函数)的的参数也为self
[self.view addSubview:[[UIView alloc] init]];
};
}
@end
问题2描述:
问:如下19行开始的block,内外还需要使用weakify strongify对吗?
@interface ViewController : UITableViewController
@property (nonatomic, copy) void (^myUniqueTestBlock)(void);
@property (nonatomic, copy) void (^myAnotherUniqueTestBlock)(void);
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
@weakify(self)
self.myUniqueTestBlock = ^(void){
@strongify(self)
[self.view addSubview:[[UIView alloc] init]];
self.myAnotherUniqueTestBlock = ^(void){
[self.view addSubview:[[UIView alloc] init]];
};
};
}
@end
问题2回答:同上,要用,不然还是拿的self