I’ve been ramping up on iPhone development, and with the NDA still in place (as far as I know), I haven’t been able to blog about what I’ve written/learned. And with that, it’s been quiet in here. Too get back into this, let’s continue to spend some more time on Objective-C…
The properties feature in Objective-C is your friend. Once you’ve written a few classes and manually wrote the accessors (getters and setters), you’ll quickly understand why properties are a good thing.
In addition to automatic creation of getters/setters, there is an option to use dot syntax in place of the traditional [receiver message] format.
I want to point out one little nuance when working with properties, setters and dot syntax , that I didn’t find to be particularly intuitive.
Let’s say you have a class with an interface definition such as this:
@interface SomeClass : NSObject
{
NSString *str;
NSDate *date;
}
@property (nonatomic, retain) NSString *str;
@property (nonatomic, retain) NSDate *date;
...
The implementation file might look like this:
@implementation SomeClass
@synthesize str;
@synthesize date;
...
Using this approach, with the combination of @property and @synthesize, we now have getters/setters that are automagically created for you. You can call them as expected
// Call the getter
NSLog(@"The value is: %s", [ptr str]);
// Call the setter
[ptr setStr:@"fubar"];
Using dot syntax, here is what a call to the getter would look like:
// Call the getter
NSLog(@"The value is: %@", ptr.str);
This syntactic sugar is quite handy and easy to grasp, for the most part (even more so if you come from languages such as Java).
Everything is pretty much as expected up to this point. The whole reason for this tip is to callout the syntax for the setter when using dot syntax. Logic tells me, it should look as follows:
// Call the setter, well on second thought, maybe not
ptr.setStr = @"Testing this";
Seems reasonable doesn’t it? It effectively matches the setter method of the [receiver message] approach. However, the correct syntax is:
// Call the setter
ptr.str = @"Testing this";
The first time I ran across a setter used this way I stopped, scratched my head a few times, scrunched up my face and probably mumbled something along the lines of "what the…"
As you dig deeper into Objective-C, and even more so, as you look into the examples that are included with the iPhone SDK, you’ll want to make note of this, as properties are used extensively throughout the code.
The format (for the setter) when using dot syntax takes some getting used to. However, hopefully this little tip will clear up the confusion until you are used to seeing this style of setter.