tags:

views:

128

answers:

3

I'm new to Objective-C (and stackoverflow) and I'm a little turned around about best practices with regards to properties.

My understanding is that when you're completely done with a property you can avoid bugs by releasing them and then immediately setting to nil so that subsequent messages also return nil instead of an exception.

[myProperty release], myProperty = nil;

However, when it comes to dealloc for 'copy' and 'retain' properties is there any need to do both? or does a simple

[myProperty release] cut it? Also, am I correct that I don't need to release 'assign' properties in dealloc?

Thanks!

+5  A: 

Do release, but don't bother setting to nil. Setting to nil via your @synthesized setter:

self.myProperty = nil

will release your old value as part of the reassignment (though as noted in the comments, may have unwanted side effects), but simply assigning nil to your member variable:

myProperty = nil

will not.

[myProperty release]

is all you need.

(and you are correct about "assign" properties.)

Seamus Campbell
+1 that the release is all you need, but I'd caution against using `self.myProperty = nil` in `dealloc` (it could fire KVO methods and notify observers to try and access a partially deallocated object...)
Dave DeLong
As Dave says, current recommended (by Apple) practice is not to use the accessors to assign nil (and hence release) in dealloc. Not only could it fire KVO methods, but the set accessor might have been overridden by a subclass.
JeremyP
A: 

@Dave DeLong and JeremyP: I think we could say “using inherited messages (direct or indirect by one, calling some part from super) whil „building“ an object (by init…, new… or copy…) is like building a house and placing the roof on it while nobody is sure, if the basement allready is there. And doing so while dealloc might be an equivalent to tear down that house, starting by knocking down the foundation walls, not being sure if being inside its cellar”.

While using methods without any inheritance might do this too – but if thei’re your own, you can (and have) to controll it.

Greetings

Objective Interested Person
A: 

@Dave DeLong: When the dealloc method of an object is performed, the object is no longer being used. All kvo observers should be removed by that moment, otherwise a waning will be dropped. And anyways - even IF an observer would see the change the object would still exist (at least partially).

The overridden accessor is the right argument I think. However, for your own classes it might still be simpler to use the accessor. Especially when using synthesized methods, where you know the semantics but no details about the accessor...

Max Seelemann