Stephen Melvin
Stephen Melvin

Reputation: 3785

Naming convention of instance variables when synthesizing properties

When synthesizing properties in Objective-C, it's recommended that you dont simply write:

@synthesize window; 

but rather

@synthesize window = _window;

The reasoning is that you don't want your instance variable named the same as your getter method or "bad things can happen".

I've always used @synthesize var1, var2, etc in my apps without "bad things" happening. What sort of bad things could happen?

Upvotes: 4

Views: 363

Answers (2)

gnasher729
gnasher729

Reputation: 52538

The biggest reason for using the leading underscore in instance variables (like _myProperty) is that when people read the code with the leading underscore, they know that you are using an instance variable, not a local variable, a global variable, or forgot to write "self." like self.myProperty, and that you did this intentionally.

Before ARC, _myProperty wouldn't do any reference counting, while self.myProperty would (for "retain" / "strong" properties). With ARC when you are using "copy" properties, _myProperty does reference counting but still does no copying, so there is still some difference. The most important difference is that _myProperty won't trigger any observers.

Upvotes: 0

Abizern
Abizern

Reputation: 150605

Bad things used to happen, particularly in the pre-ARC days when people would assign objects to the storage iVar instead of the property. If this was done by accident, then the memory management implied by the synthesized setter wouldn't be applied, leading to leaks, or premature releases.

I use to do it the simple way, but now I use prefixes. I don't declare my iVar themselves anymore, I let the modern runtime take care of that for me. I use prefixes so that I don't accidentally use an iVar like a local variable.

Also - I tend to refer to my properties as self.iVar almost everywhere in my classes. This is so that I can use lazy loaded properties when I want to without worrying about which ones are and are not lazily loaded.

Upvotes: 5

Related Questions