Declaring instance variables with @synthesize


#1

Working with the Apple documentation along side, I’ve observed (in: Your 1st & 2nd iOS App) that Apple is not including the instance variable declarations.

Instead, they are writing something like:

@synthesize productName = _productName;

I understand the desire to ‘document’ code and agree with that philosophy, but am missing the affect this has later on using accessors in the implementation code. If possible, can someone please say a few words about using accessors in the implementation in this way.


#2

In general I find the underscore naming to be a strange convention.

The idea is that @synthesize creates accessors to an instance variable. The value after the = gives you direct access to the ivar.

So if you did something like:

Then someVariable is going to call the appropriate setter or getter and _someVariable is going to directly access the ivar.

Since directly accessing the ivar is against the more strict rules of Objective-C I sometimes wonder why the underscore name is included at all in the Apple templates. @synthesize on its own makes a nice clean accessor that we can use.

When you are using the modern runtime (64-bit Cocoa, or CocoaTouch) you don’t need to actually declare the ivars in the header at all. Just the @property and @syntesize statements will do.


#3

@macshome,

Thank you for taking the time to write that simple, clear explanation. It helps quite a bit.


#4

One of the motivations for the leading underscore is to prevent a class of errors introduced by dot notation. Objective-C dot notation is mentioned only briefly in the book saying “it exists, and I’m not going to talk about it again.” I believe it’s a handy notation for an experienced developer, but is often very confusing for someone new to the platform. (as if Objective-C wasn’t confusing enough to start out with!)

If you’re familiar with dot notation, it fixes the error of assigning to an instance variable (propname = whatever;) when you really meant to do “self.propname = whatever;” to get the behavior of the synthesized accessors. One of the common pre-ARC bugs was that you might not actually hang on to an object you were expecting to be retained, leading to difficult-to-debug crashes in the future.