• Advertisement
Sign in to follow this  

Confusion about @synthesize in Objective C

This topic is 3101 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Anytime while using C++ and I'd hear about setter and getter functions any book/professor/whatever would always say "Its so no functions or anything can mess with the internal data of the class". This never made sense to me (seeing how as a setter can access the class anyway but whatever) but I did it anyway because that is what the standard seems to be. Fast forward to now where I am learning Objective C. Same deal, when I ran across accessor and mutator methods I would make them just because it was the standard, then comes the @synthesize that makes them for me. When programming, it looks just like I am accessing the instance variables so what is the point in hiding them? I'm pretty sure there is some REAL reason but no programming book or college professor (I've had many) can ever give me a real reason why these are necessary other then with them it "fully encapsulates" the class. (If this is the case thats fine but I'm sure there is probably something more to it.) Is there something I am missing here? Is it maybe any program I make just doesn't have a need for them? Can someone please clarify?

Share this post


Link to post
Share on other sites
Advertisement
In theory, you only need to implement accessors for instance variables where setting/retrieving the variable needs to trigger some behaviour (i.e call a function to transform the value/perform processing).

Unfortunately, up until properties came along, there was no uniform interface between plain instance variables, and those which required effects, so accessor methods were often written for *every* instance variable - just for convenience.

@synthesise just creates accessor methods which do nothing (beside setting the named instance variable), so that they will work the same as custom accessors.

Share this post


Link to post
Share on other sites
Getters and setters provide a level of abstraction between you and the data. Your external class is just calling the "set" method on your target object but inside that method you could be doing all sorts of manipulation of checking before actually setting the variable. As usual, the abstraction allows you to easily change code later without having worry too much about your calling classes.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement