I’m a little confused about the principles of autoreleasing objects from custom init methods. For example:
- (id)initWithId: (unsigned long)personID {
self = [super init];
if (self) {
self.ID = personID;
}
return self;
}
According to the objc coding conventions I must autorelease self on return. But that kind of code keeps crushing. Am I’m missing something? Should I autorelease only those objects I create manually in those methods, but not “self”, like this?
- (id)makeWithId: (unsigned long)personID {
Person *obj = [[Person init] alloc];
if (obj) {
obj.ID = personID;
}
return [obj autorelease];
}
Thanks in advance.
In Cocoa, there is this convention:
allocornewreturn an object with retain count +1Note that with the
initmethod you posted above, an object isn’t created. The previousalloccall creates the object. This just sets it up and makes it ready for use.As for your
makeWithIdmethod, you’ve confused two concepts. A factory method like this should be a class method (i.e. declared with a+, not a-). Then you will use it likeAs it stands, you’re returning a different object than the receiver of the method call. That means that when you do
The
Personobject created withallochas been leaked, andpis autoreleased.So, to summarise, return autoreleased objects from class ‘factory’ methods, and don’t do any memory management in
initmethods.