Centurion Centurion - 4 years ago 95
Objective-C Question

Does omitting the declaration of ivars for properties might cause trouble or leaks?

I started to learn and develop for iOS4, so I just skipped the old ivar declaration convention and started to use pure properties without even declaring ivars. Everything went fine, I even released my first homemade app on the app store. But then at my dev company, guys told me that they are still using old convention and are declaring ivars with underscored names, use properties and synthesize them (see example at the end). They also said that they are using properties only when outside access to ivars is needed, and for inner access they use direct ivars (for custom classes). I was told that they are doing so because they were experiencing some weird leaks, that sometimes appeared when using custom classes and nil'ying their properties in viewDidUnload (because setting nil to properties sometimes didn't release those ivar objects)

Just wondering why should I bother to use ivar declaration when using properties and synthesize does all the needed stuff. I can even access ivars directly using their names without self in dealloc. So, does anybody got problems with that or many of you still are sticking with the old declaration convention?

@interface ContactModel : NSObject {

NSString *_firstName;

@property (nonatomic, retain) NSString *firstName;


@implementation ContactModel

@synthesize firstName = _firstName;

[_firstName release];
[super dealloc];

Should also note, that Apple still uses that old declaration style when generating main app delegate class file and synthesize window=_window. Hm, currently, I'm a little bit confused about what convention should I take, so any ideas are welcome :)

Answer Source

In the modern runtime you don't need the ivar declaration, but synthesize a=_a is still useful to make a distinction between self.a (accessors) and _a (direct access). If @property/@synthesize was leaking I think we should know it by now.

AFAIK using ivars instead properties is only useful if you want @protected access (access to subclasses only), or support the old runtime.

In dealloc you should release the property directly whether you are using ivar declaration and @properties, and optionally you can nil or not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download