May 27, 2014

Fast food objective-c (part 2) : Accessors

Accessors

All instance variables are private in Objective-C by default, so you should use accessors to get and set values in most cases. There are two syntaxes. This is the traditional 1.x syntax:
[photo setCaption:@"Day at the Beach"];
output = [photo
caption];
The code on the second line is not reading the instance variable directly. It's actually calling a method named caption. In most cases, you don't add the "get" prefix to getters in Objective-C. 
Whenever you see code inside square brackets, you are sending a message to an object or a class.

Dot Syntax

The dot syntax for getters and setters is new in Objective-C 2.0, which is part of Mac OS X 10.5:
photo.caption = @"Day at the Beach";
output = photo
.caption;
You can use either style, but choose only one for each project. The dot syntax should only be used setters and getters, not for general purpose methods.

No comments:

Post a Comment