views:

97

answers:

2

Hello all,

I have a simple question, that in a class I have a variable with property retain

//Classs ArrayClass has this array
@property(nonatomic, retain) NSMutableArray *array;

Now when I do

self.array = [SomeClass getArray];

I need to release the array...

Now If I have object of ArrayClass and when I do

arrayClassObj.array = [SomeClass getArray];

So in this case, Is the setter method is called? Do I need to release in this case.

+2  A: 

In both cases the object being assigned it's array property from [SomeClass getArray] will need to release it itself, unless you set the property to nil.

The following is required by the class owning the array property.

// ArrayClassObject dealloc (self in first example)
-(void)dealloc
{
    [array release];
    [super dealloc];
}

When you assign the property then assign it nil, the [array release] is still required in the dealloc method, but since you're assigning nil to it, it won't have any effect.

// someArrayObj must have [array release] in its dealloc method
someArrayObj.array = [SomeClass getArray];

// But you can do it manually by assigning nil
someArrayObj.array = nil;
Nick Bedford
+3  A: 

The setter generated by @synthesize will (since you told it to retain) handle the retaining and releasing for you. If you override it, it's on you.

In your dealloc, don't forget to release it as well -- safe, don't forget, because messages to nil are not errors (and you should be setting a var to nil if you're through with it).

Jed Smith
The setter generated by @synthesize will also create the required notifications to make the property KVO compliant. Again if you override, this is your responsibility.
nall
nall: No, that's not true. When something observes a property of an object, KVO wraps the KVC-compliant accessor methods for that property of that object. Your setter method does *not* need to post its own KVO notifications, because KVO's wrapper implementations will do that for you. You only need to conform to the KVC-compliant accessor selector formats.
Peter Hosey
I've learned something new, thanks.
nall