Using the _variable


Still a little confused by this underscore in the synthesize directive. I see it in Apple’s examples a lot, so I added it to my Person.m file

@synthesize personName = _personName;
@synthesize expectedRaise = _expectedRaise;

The project was working fine until this chapter where the encoders were not able to write out the values. Once I removed the underscores from both @synthesize directives the coders worked and the values were written out to the document file.

I thought the underscores were the getter and setter for the variable. Should we avoid them when doing KVC?



When you @synthesize your getter and setter, and use the second part (after the equals), you are telling the compiler what instance variable to use for this property. Like this:

If you leave off the equal sign and everything after it, the i-var (instance variable) name will be the same as the property name. Because the code in the Archiving chapter uses the i-vars directly, if you change the @synthesize statements in this way there will not be the proper relationship between setter/getter and i-var. My guess is that this is what happened in your exercise.

The underscore prefix works fine with KVO/KVC, particularly in the case of properties, because properties is checked for first. The compiler will also check for an underscore prefix if there is no property or instance variable with the KVC name. For example, if you are using KVC for “name” the runtime will check for a property called “name”, then an i-var called “name”, and finally an i-var called “_name”.