Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why shouldn't I use the getter to release a property in objective-c?

I was told by a fellow StackOverflow user that I should not use the getter method when releasing a property:

@property(nonatmic, retain) Type* variable;
@synthesize variable;

// wrong
[self.variable release]; 

// right
[variable release]; 

He did not explain in detail why. They appear the same to me. My iOS book said the getter on a property will look like this:

- (id)variable {
    return variable;
}

So doesn't this mean [self variable], self.variable, and variable are all the same?

like image 621
JoJo Avatar asked Aug 31 '11 19:08

JoJo


People also ask

What method is automatically called to release objects in Objective-C?

The NSArray class method array returns a newly initialized array that is already set for autorelease. The object can be used throughout the method, and its release is handled when the autorelease pool drains. At the end of this method, the autoreleased array can return to the general memory pool.

What is Property in Obj C?

Properties in Objective-C allow you to provide a well-defined interface for other classes to manipulate (i.e. get or set) attributes of a class. They also insulate external classes from the implementation details of the attributes (this separation of function and implementation is known as encapsulation).


2 Answers

For a retained property with no custom accessor, you can release the object by:

self.variable = nil;

This has the effect of setting the ivar (which may not be called 'variable' if you have only declared properties) to nil and releasing the previous value.

As others have pointed out, either directly releasing the ivar (if available) or using the method above is OK - what you must not do is call release on the variable returned from a getter.

like image 100
jrturton Avatar answered Nov 16 '22 04:11

jrturton


You can optionally write custom getter behavior, which may result in completely different behavior. So, you cannot always assume that [variable release] has the same results as [self.variable release].

As well, you can write custom properties without an exclusive ivar backing them... it can get messy fast if you start releasing objects from references returned by getters!

There may be additional reasons that I'm unaware of...

like image 34
MechEthan Avatar answered Nov 16 '22 03:11

MechEthan