Stormherz
Stormherz

Reputation: 376

Autorelease in custom init methods

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.

Upvotes: 0

Views: 478

Answers (2)

Chakalaka
Chakalaka

Reputation: 2827

You do not allocating anything, so you don't have to release something.

You can autorelease your object when you create it.

YourClass *yourOblect = [YourClass alloc] initWithId:27] autorelease];
[yourObject doSomething];
.....

Upvotes: 2

joerick
joerick

Reputation: 16448

In Cocoa, there is this convention:

  • Methods that start with alloc or new return an object with retain count +1
  • all other methods that create an object return an autoreleased object.

Note that with the init method you posted above, an object isn't created. The previous alloc call creates the object. This just sets it up and makes it ready for use.

As for your makeWithId method, 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 like

Person *p = [Person makeWithId:3];

As it stands, you're returning a different object than the receiver of the method call. That means that when you do

Person *p = [[Person alloc] makeWithId:3];

The Person object created with alloc has been leaked, and p is autoreleased.

So, to summarise, return autoreleased objects from class 'factory' methods, and don't do any memory management in init methods.

Upvotes: 3

Related Questions