Objective-C Dot语法和Init

Mar*_*ell 9 syntax objective-c

我已经阅读了一些片段,提到你不应该在init或dealloc方法中使用dot-notation.但是,我似乎永远无法找出原因.一篇文章顺便提到它与KVO有关,但没有更多.

@interface MyClass : NSObject {
    SomeObject *object_;
}
@property (nonatomic, retain) SomeObject *object;
@end
Run Code Online (Sandbox Code Playgroud)

这个实现不好?

@implementation MyClass 

@synthesize object = object_;

- (id)initWithObject:(SomeObject *)object {
    if (self = [super init]) {
        self.object = object;
    }

    return self;
}
@end
Run Code Online (Sandbox Code Playgroud)

但这很好吗?

@implementation MyClass 

@synthesize object = object_;

- (id)initWithObject:(SomeObject *)object {
    if (self = [super init]) {
        object_ = [object retain];
    }

    return self;
}
@end
Run Code Online (Sandbox Code Playgroud)

在init中使用点符号有哪些缺陷?

Jer*_*myP 26

首先,它不是具体的点符号,它是你不应该使用的访问器.

self.foo = bar;
Run Code Online (Sandbox Code Playgroud)

完全相同

[self setFoo: bar];
Run Code Online (Sandbox Code Playgroud)

他们在init/dealloc中都不满意.

主要原因是因为子类可能会覆盖您的访问器并执行不同的操作.子类的访问器可能假设一个完全初始化的对象,即子类的init方法中的所有代码都已运行.事实上,当你的init方法运行时,它都没有.类似地,子类的访问器可能依赖于子类的dealloc方法没有运行.当你的dealloc方法运行时,这显然是错误的.