开发者

Objective-C Dot Syntax and Init

开发者 https://www.devze.com 2023-01-05 01:49 出处:网络
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

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

This implementation is bad?

@implementation MyClass 

@synthesize object = object_;

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

    return self;
}
@end

But this is good?

@implementation MyClass 

@synthesize object = object_;

- (id)initWithObject:(SomeObject *)object {
 开发者_StackOverflow中文版   if (self = [super init]) {
        object_ = [object retain];
    }

    return self;
}
@end

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;

is identical to

[self setFoo: bar];

and they are both frowned upon within init/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.


The reasons I've heard mainly crop up due to when you write your own setters/getters. When using the default @synthesized versions of the methods it won't cause much of an issue. When you write your own setter though, it is generally going to have a sideeffect on your class. This sideeffect is probably not wanted in the init, or even is going to cause issues if it references other ivars that haven't been created yet. Same issue in the dealloc, if you have a sideeffect, it has potential to blow up.

0

精彩评论

暂无评论...
验证码 换一张
取 消