views:

22

answers:

2

If I have a function like this

void setSomeObject( SomeObjectClass obj /*, and some other params*/ )
{
  [_previous autorelease];
  _previous = obj;
}

As far as I understood it the autorelease message is sent to the object itself (not _previous) so at one point, sometime when setSomeObject goes out of scope the original object is autoreleased (if any). Is this correct? I am not using properties but I guess by using them the release of the previous object would be automatic when I do self.previous = obj; ?

A: 

No that is incorrect.

[_previous autorelease] sends the autorelease message to _previous. That is the meaning of this syntax.

Gary
+1  A: 

When you send an -autorelease message to an object, it's added to the active NSAutoreleasePool, which is emptied when the run loop runs. If you say [_previous autorelease], only that object will be autoreleased, and if you then say _previous = obj, that only changes the variable's reference. The old object is still autoreleased.

If you're doing this in a setter method, this is what the pattern generally is:

- (void)setSomeObject:(MyObjClass *obj) {
    if (obj != someObject) {
        [someObject release];
        someObject = [obj retain]; // or copy, depending on what you want
    }
}
jtbandes
so in a sense one could write also [_previous autorelease] however it is not standard? (although need to make sure its not already pointing to the same object)
BuggerMe
Yes. If you recall the fundamental memory management rules, any object of which you have ownership (gained by alloc/new/copy/retain) must be later relinquished (release or autorelease), so either will work. But in this case there's no need for autorelease, since you don't need to refer to the object in the rest of the function.Another way to avoid all this is to use regular @property (copy) or (retain) with @synthesize, which creates accessor methods for you, and instead of doing all the stuff I wrote in my answer, you can just do `self.someObject = obj`.
jtbandes