Confusion about @synthesize in Objective C

Started by
2 comments, last by Chrono1081 14 years, 9 months ago
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?
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.

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

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.
Thank you guys for the clarification :)

This topic is closed to new replies.

Advertisement