Why synthesize?


#1

As a new programmer to C, Objective-C, and all other flavors… I’m enjoying learning this language.

Every time we declare a property in the *.h file, we synthesize it in the *.m file. With much of the workflow simplified, as mentioned in the book regarding the setPropertyName and getPropertyName methods done for us automatically, why wouldn’t the synthesizing be done automatically too?

It made me wonder if there was ever a time that you wouldn’t synthesize the property. If so, what is that time and would I even understand it at this point?

Thanks,
Phil


#2

If you’re all set on creating properties (so you want variables that other objects want to access instead of keeping them private), then the only reason you wouldn’t synthesize (according to my understanding of the book) is if you had to over ride both the getter and setter methods, as at that stage there essentially wouldn’t be a point because you would be writting out the methods anyway.

If there was a variable I wanted to do custom setting for like the setContainedItem in the book, if when objects accessed that variable I also wanted it to do something like NSLog a statement as a reminder then there wouldn’t be any point in asking xCode to automatically write out those statements because I’m rewriting them both anyway.

Also if there was a readonly value (which therefore wouldn’t give you a setter) and you wanted to return something a little more custom than just the value of the variable so you were over riding the getter, again there wouldn’t be a point as you are writing the method anyway.

Does that help?


#3

That makes sense, yeah. Thanks.


#4

One thing that was mentioned in the Stanford course (available for free on iTunes U) was that even if you write your own setter and getter for a @property, it’s still valuable to @synthesize because it generates an instance variable for that @property as well. And this is actually one thing I’ve noticed as a difference in semantics between BNR and other resources is that others tend to @synthesize in this general format:

The point as I understand it is to avoid confusion of having the @property and the instance variable named the same thing (which is the default as supplied by XCode). So they add a _ just to differentiate.