May 27, 2014

Fast food objective-c (part 9) : Properties

When we wrote the accessor methods for caption and author earlier, you might have noticed that the code is straightforward, and could probably be generalized. 

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:
#import 

@interface Photo : NSObject {
    NSString* caption;
    NSString* photographer;
}
- (NSString*) caption;
- (NSString*) photographer;

- (void) setCaption: (NSString*)input;
- (void) setPhotographer: (NSString*)input;

@end
Here's what it looks like once converted to properties:
#import 

@interface Photo : NSObject {
    NSString* caption;
    NSString* photographer;
}
@property (retain) NSString* caption;
@property (retain) NSString* photographer;

@end
The @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. 
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];
}

@end
The @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