Properties are a feature in Objective-C that allow us to automatically generate accessors, and also have some other side benefits. Let's convert the Photo class to use properties.
Here's what it looked like before:
#importHere's what it looks like once converted to properties:@interface Photo : NSObject { NSString* caption; NSString* photographer; } - (NSString*) caption; - (NSString*) photographer; - (void) setCaption: (NSString*)input; - (void) setPhotographer: (NSString*)input; @end
#importThe @property is an Objective-C directive which declares the property. The "retain" in the parenthesis specifies that the setter should retain the input value, and the rest of the line simply specifies the type and the name of the property.@interface Photo : NSObject { NSString* caption; NSString* photographer; } @property (retain) NSString* caption; @property (retain) NSString* photographer; @end
Now let's take a look at the implementation of the class:
#import "Photo.h" @implementation Photo @synthesize caption; @synthesize photographer; - (void) dealloc { [caption release]; [photographer release]; [super dealloc]; } @endThe @synthesize directive automatically generates the setters and getters for us, so all we have to implement for this class is the dealloc method.
Accessors will only be generated if they don't already exist, so feel free to specify @synthesize for a property, then implement your custom getter or setter if you want. The compiler will fill in whichever method is missing.
There are many other options for the property declarations, but those are outside of the scope of this tutorial.
No comments:
Post a Comment