views:

142

answers:

2

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 {
    if (self = [super init]) {
        object_ = [object retain];
    }

    return self;
}
@end

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

+1  A: 

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.

Joshua Weinberg
+6  A: 

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.

JeremyP
Would whoever just down voted this answer please explain why they did it?
JeremyP