when to copy/retain/assign ivars in Objective-C
Aug 24, 2011
Dick Brouwer
1 minute read

Use copy instead of retain for all classes that have a mutable variant. Eg. NSAArray, NSSet, NSDictionary, NSData, NSCharacterSet, NSIndexSet, and NSString. Why? Because if someone passes you a mutable variant which you retain, they can then change it afterwards.

Assign a property in the case you can’t retain the value (such as non-object types like BOOL or NSRect) or when retaining it would cause unwanted side effects

Delegates are to be assigned to avoid circular references. In fact, everything that is not an owning relationship should use assign rather than copy or retain.

ps. don’t forget to set delegates to nil in dealloc. Aka, don’t release them, but for example a class that sets locationManager.delegate = self, should do locationManager.delegate = nil in dealloc, to prevent the locationManager to send messages to a released object.

comments powered by Disqus