Properties
A property declares a piece of an object's state together with its accessor methods. One line:
@property NSString *name;makes the compiler synthesize three things for you:
| Generated | Name | Purpose |
|---|---|---|
| instance variable | _name |
the storage |
| getter | - (NSString *)name |
returns the value |
| setter | - (void)setName:(NSString *)name |
changes the value |
Using the accessors
Dot syntax and bracket syntax call exactly the same methods:
#import <Foundation/Foundation.h>
@interface Player : NSObject
@property NSString *name;
@property NSInteger level;
@property BOOL online;
@end
@implementation Player
@end
int main(void) {
@autoreleasepool {
Player *p = [Player new];
[p setName:@"Kira"]; // bracket syntax
p.level = 7; // dot syntax: calls setLevel:
p.online = YES;
NSLog(@"%@ is level %ld", [p name], (long)p.level);
p.level += 1; // getter, add, setter
NSLog(@"after level up: %ld", (long)p.level);
NSLog(@"online: %@", p.online ? @"YES" : @"NO");
}
return 0;
}Kira is level 7
after level up: 8
online: YES
Even an empty @implementation Player @end works: everything for the three properties was generated.
Custom accessors
You can write the getter or setter yourself to add behaviour such as validation. Inside them, use the instance variable _level directly. Writing self.level = … inside setLevel: would call the setter again and recurse forever.
#import <Foundation/Foundation.h>
@interface Thermostat : NSObject
@property (nonatomic) double target;
@end
@implementation Thermostat
- (void)setTarget:(double)target {
if (target < 10) {
target = 10;
} else if (target > 28) {
target = 28;
}
NSLog(@"target set to %.1f", target);
_target = target;
}
@end
int main(void) {
@autoreleasepool {
Thermostat *t = [Thermostat new];
t.target = 21.5;
t.target = 35;
t.target = -4;
NSLog(@"final target: %.1f", t.target);
}
return 0;
}target set to 21.5
target set to 28.0
target set to 10.0
final target: 10.0
Note: The
(nonatomic)in this example is a property attribute, explained in the next lesson. Properties areatomicby default, and clang warns if you write only one accessor of an atomic property yourself, because it can't make your half thread-safe. Writing a custom accessor? Make the propertynonatomic.
Computed (derived) properties
A readonly property with a custom getter doesn't need storage at all: it computes its value from other properties.
#import <Foundation/Foundation.h>
@interface Rectangle : NSObject
@property double width;
@property double height;
@property (readonly) double area;
@property (readonly, getter=isSquare) BOOL square;
@end
@implementation Rectangle
- (double)area {
return self.width * self.height;
}
- (BOOL)isSquare {
return self.width == self.height;
}
@end
int main(void) {
@autoreleasepool {
Rectangle *r = [Rectangle new];
r.width = 4;
r.height = 2.5;
NSLog(@"area %.1f, square? %d", r.area, r.isSquare);
r.height = 4;
NSLog(@"area %.1f, square? %d", r.area, [r isSquare]);
}
return 0;
}area 10.0, square? 0
area 16.0, square? 1
getter=isSquare renames the getter so that a BOOL reads like a question. The property is still called square, but its getter is isSquare.
ivar or self.property?
Inside a class, self.name goes through the accessor methods, while _name touches the storage directly.
| Use | When |
|---|---|
self.name |
almost everywhere: custom setters, copy semantics and change notifications (KVO) keep working |
_name |
inside the property's own getter and setter, in init and in dealloc |
Note: You can still rename the backing variable with
@synthesize name = myName;, and older code often contains@synthesize name;lines. Since Xcode 4.4 they are optional: synthesis happens automatically.
Properties in practice
#import <Foundation/Foundation.h>
@interface Order : NSObject
@property NSString *product;
@property NSInteger quantity;
@property double unitPrice;
@property (readonly) double total;
@end
@implementation Order
- (double)total {
return self.quantity * self.unitPrice;
}
@end
int main(void) {
@autoreleasepool {
Order *order = [Order new];
order.product = @"Notebook";
order.quantity = 3;
order.unitPrice = 2.40;
NSLog(@"%ld x %@ = %.2f", (long)order.quantity, order.product, order.total);
}
return 0;
}3 x Notebook = 7.20
Test yourself
Which setter does @property NSInteger score; generate?
- - (void)score:(NSInteger)v
- - (void)setScore:(NSInteger)score
- - (void)set_score:(NSInteger)v
- - (NSInteger)setScore
Why must a custom setLevel: use _level = level; instead of self.level = level;?
- self is nil inside a setter
- self.level = calls setLevel: again, recursing forever
- Dot syntax isn't allowed in methods
- There is no difference
What does getter=isSquare do?
- Makes the property read-only
- Renames the getter method to isSquare
- Creates a second property
- Makes the property a class property