Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Objective-C Basics (Retired) Introduction to Objective-C Introducing @property

John Saunders
John Saunders
288 Points

Benefit of setting "setters and getters" if @property is more simple?

Is there an advantage of using setters and getters versus only @property ? It seems the @property declarative is easier then the setters and getters.

3 Answers

Gareth Borcherds
Gareth Borcherds
9,372 Points

The way I understand this is that sometimes you'll want to use a custom function to set your variable, like maybe using an if condition or something. So the benefit would be that you can enhance your property setting and getting. There are a couple of videos in some of the other challenges where Amit does this for setting default values or default arrays for some of the class properties that he sets. As you go along you'll see this more clearly than I can explain in this response :)

Imagine that you want to add objects to an array property. If the property is not initialized you get an error. So in the getter method you can "lazy initialize" the array. Basically you just create one if there is none. For example:

if (!array) _array = [[NSArray alloc] init]; return _array

@property alone saves us the trouble of writing our own setters and getters but sometimes we want to modify one of them, or maybe both. Don't forget to @synthesize the property in case you do so.

Hope this answers your question!