Apple建议“不要在初始化方法和dealloc中使用访问器方法”与本文档: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html
如果我想在初始化方法中设置块,阻止对属性的引用,我如何编写更好的代码?
typedef void(^customBlock)();
@interface CustomObject : NSObject
@property (nonatomic, strong) NSString *string;
@property (nonatomic, copy) customBlock customBlock1;
@property (nonatomic, copy) customBlock customBlock2;
@end
@implementation CustomObject
- (instancetype)init {
self = [super init];
if (self) {
__weak __typeof(self) weakSelf = self;
_customBlock1 = ^ {
__typeof(self) strongSelf = weakSelf;
strongSelf -> _string = @"string by iVar";
};
_customBlock2 = ^{
weakSelf.string = @"string by accessor";
};
}
return self;
}
@end
答案 0 :(得分:0)
_customBlock1 =[ ^ {
__typeof(self) strongSelf = weakSelf;
strongSelf -> _string = @"string by iVar";
} copy];
这可以达到调用setter方法的效果,因此避免了在Initializer方法中使用accessor方法的副作用。