Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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!