views:

83

answers:

4

From Apple documentation about Memory Management :

The only places you shouldn’t use accessor methods to set an instance variable are in init methods and dealloc. To initialize a counter object with a number object representing zero, you might implement an init method as follows:

To allow a counter to be initialized with a count other than zero, you might implement an initWithCount: method as follows:

- initWithCount:(NSNumber *)startingCount {
    self = [super init];
    if (self) {
        count = [startingCount copy];
    }
    return self;
}

Why not ?

+1  A: 

just from an OOP point of view (since I have no experience with objective-c), you would not use methods of the object which is currently being constructed. This is possible in some languages, but you already have access to the private variables. The object construction isn't completed yet, so it isn't ready to be operated on. Once the object is constructed it is in a known good state (or so it is assumed) and it can perform.

Scott M.
Yes, I understand that if you redefined the init method that could be a problem of self recursion.But if you define another method like initWithCount, I don't get the point from a technical point of view.
Pierre Valade
A: 

Even if I can't find a clear and simple answer, I guess that Perspx is right, this is a duplicate with this question.

Pierre Valade
+1  A: 

See my answer to this question.

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.

To expand on your example, if you had instead done

- initWithCount:(NSNumber *)startingCount {
    self = [super init];
    if (self) {
        [self setCount: [startingCount copy]];
    }
    return self;
}

but a subclass had overridden setCount: to do something other than set your count variable, you could be in trouble.

JeremyP
A: 

Building and tearing down a house isn’t the same than living in it: http://stackoverflow.com/questions/3402234/properties-in-dealloc-release-then-set-to-nil-or-simply-release/3408931#3408931

Greetings

Objective Interested Person