Objective-C点语法和初始化

Objective-C点语法和初始化

问题描述:

我已经阅读了许多片段,其中提到您不应在init或dealloc方法中使用点符号.但是,我似乎永远无法找出原因.顺带一提,它确实与KVO有关,但仅此而已.

I have read a number of snippets that mention you should never use dot-notation within your init or dealloc methods. However, I can never seem to find out why. One post did mention in passing that it has to do with KVO, but no more.

@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中使用点符号有什么陷阱?

What are the pitfalls of using dot-notation inside your init?

首先,它不是点号,而是您不应该使用的访问器.

Firstly, it's not the dot notation specifically, it's the accessors that you shouldn't use.

self.foo = bar;

[self setFoo: bar];

,它们都在init/dealloc中不满意.

and they are both frowned upon within init/dealloc.

主要原因是因为子类可能会覆盖您的访问器并执行其他操作.子类的访问器可能假设一个完全初始化的对象,即子类的init方法中的所有代码都已运行.实际上,当您的init方法运行时,它们都没有.同样,子类的访问器可能取决于子类的dealloc方法 not 是否已运行.当您的dealloc方法正在运行时,这显然是错误的.

The main reason why is because a subclass might override your accessors and do something different. The subclass's accessors might assume a fully initialised object i.e. that all the code in the subclass's init method has run. In fact, none of it has when your init method is running. Similarly, the subclass's accessors may depend on the subclass's dealloc method not having run. This is clearly false when your dealloc method is running.