Objective-C点语法和Init
发布时间:2020-12-16 03:12:27 所属栏目:百科 来源:网络整理
导读:我已经读了很多片段,提到你不应该在你的init或者dealloc方法中使用点符号.但是,我似乎无法找出原因.一个帖子经常提到它与KVO有关,但没有更多. @interface MyClass : NSObject { SomeObject *object_;}@property (nonatomic,retain) SomeObject *object;@end
我已经读了很多片段,提到你不应该在你的init或者dealloc方法中使用点符号.但是,我似乎无法找出原因.一个帖子经常提到它与KVO有关,但没有更多.
@interface MyClass : NSObject { SomeObject *object_; } @property (nonatomic,retain) SomeObject *object; @end 这个实现是坏的? @implementation MyClass @synthesize object = object_; - (id)initWithObject:(SomeObject *)object { if (self = [super init]) { self.object = object; } return self; } @end 但这是好的? @implementation MyClass @synthesize object = object_; - (id)initWithObject:(SomeObject *)object { if (self = [super init]) { object_ = [object retain]; } return self; } @end 在init中使用点符号的缺陷是什么? 解决方法
首先,它不是特别的点符号,它是你不应该使用的访问器.
self.foo = bar; 是相同的 [self setFoo: bar]; 并且它们在init / dealloc中都是皱起眉头的. 主要原因是因为一个子类可能会覆盖您的访问器并执行其他操作.子类的访问器可能假定完全初始化对象,即子类的init方法中的所有代码都已运行.实际上,当init方法正在运行时,它们都没有.类似地,子类的访问器可能依赖于子类的dealloc方法没有运行.当您的dealloc方法运行时,这显然是错误的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |