Property Attributes
The words in parentheses after @property are attributes. They tell the compiler how the generated accessors should behave:
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSMutableArray *items;
@property (nonatomic, weak) id delegate;
@property (nonatomic, assign) NSInteger count;
@property (nonatomic, readonly) NSString *identifier;There are three independent groups.
1. Atomicity: atomic / nonatomic
| Attribute | Meaning |
|---|---|
atomic (default) |
the accessor always returns a whole value even if another thread sets it at the same time; slightly slower |
nonatomic |
no locking; faster |
atomic does not make your class thread-safe; it only protects a single get or set. In practice almost all Apple and app code uses nonatomic, and so does the rest of this course.
2. Access: readwrite / readonly
readwrite (the default) generates a getter and a setter; readonly only a getter. A class often exposes a property as readonly and keeps writing to its ivar internally:
#import <Foundation/Foundation.h>
@interface BankAccount : NSObject
@property (nonatomic, readonly) double balance;
- (void)deposit:(double)amount;
@end
@implementation BankAccount
- (void)deposit:(double)amount {
if (amount > 0) {
_balance += amount; // the class can still change its ivar
}
}
@end
int main(void) {
@autoreleasepool {
BankAccount *account = [BankAccount new];
[account deposit:50];
[account deposit:-10];
[account deposit:25.5];
NSLog(@"balance: %.2f", account.balance);
// account.balance = 1000000; // compile error: property is readonly
}
return 0;
}balance: 75.50
3. Memory: strong, weak, copy, assign
These decide what the setter does with the value it receives. They only matter for object types.
| Attribute | For | What the setter does |
|---|---|---|
strong (default for objects) |
objects you own | keeps the object alive as long as this object refers to it |
weak |
delegates, parents, back-references | refers without keeping alive; becomes nil automatically when the object goes away |
copy |
NSString, NSArray, NSDictionary, blocks |
stores an immutable copy of the value |
assign (default for C types) |
NSInteger, BOOL, double, structs |
plain assignment |
strong and weak are explained in depth in the memory management lessons. Here is why copy matters for strings:
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, strong) NSString *strongName;
@property (nonatomic, copy) NSString *copiedName;
@end
@implementation Person
@end
int main(void) {
@autoreleasepool {
NSMutableString *input = [NSMutableString stringWithString:@"Ana"];
Person *p = [Person new];
p.strongName = input; // keeps a pointer to the SAME mutable object
p.copiedName = input; // keeps its own immutable copy
[input appendString:@" Silva"]; // someone later changes the original
NSLog(@"strongName: %@", p.strongName);
NSLog(@"copiedName: %@", p.copiedName);
}
return 0;
}strongName: Ana Silva
copiedName: Ana
NSMutableString is a subclass of NSString, so a mutable string can be passed wherever an NSString is expected. With strong, the object's "name" silently changed behind its back. With copy, it is safe. Rule of thumb: declare NSString, NSArray, NSDictionary, NSSet and block properties as copy.
Tip: Copying an immutable
NSStringis free:copyon an immutable object just returns the same object. Socopycosts nothing in the common case.
weak in action
A weak property does not keep its object alive, and it turns into nil by itself once nobody else holds the object:
#import <Foundation/Foundation.h>
@interface Badge : NSObject
@property (nonatomic, copy) NSString *text;
@end
@implementation Badge
@end
@interface Label : NSObject
@property (nonatomic, weak) Badge *badge;
@end
@implementation Label
@end
int main(void) {
@autoreleasepool {
Label *label = [Label new];
@autoreleasepool {
Badge *badge = [Badge new]; // a strong local variable owns it
badge.text = @"NEW";
label.badge = badge;
NSLog(@"inside: %@", label.badge.text);
} // badge's only strong owner is gone
NSLog(@"outside: %@", label.badge ? @"still there" : @"nil");
}
return 0;
}inside: NEW
outside: nil
Other attributes
| Attribute | Example | Effect |
|---|---|---|
getter= |
(getter=isEnabled) BOOL enabled |
renames the getter |
setter= |
(setter=setDarkMode:) BOOL dark |
renames the setter (rare) |
nullable / nonnull |
(nonatomic, nullable) NSString *nickname |
documents whether nil is allowed (see Nullability) |
class |
(class, readonly) NSInteger count |
a class property, implemented with + methods |
A typical, well-written class header looks like this:
#import <Foundation/Foundation.h>
@interface Song : NSObject
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSArray *artists;
@property (nonatomic, assign) NSInteger durationSeconds;
@property (nonatomic, assign, getter=isFavorite) BOOL favorite;
@property (nonatomic, readonly) NSString *formattedDuration;
@end
@implementation Song
- (NSString *)formattedDuration {
return [NSString stringWithFormat:@"%ld:%02ld",
(long)(self.durationSeconds / 60), (long)(self.durationSeconds % 60)];
}
@end
int main(void) {
@autoreleasepool {
Song *song = [Song new];
song.title = @"Night Drive";
song.artists = @[@"Lumen", @"Kael"];
song.durationSeconds = 247;
song.favorite = YES;
NSLog(@"%@ by %@ (%@)%@", song.title,
[song.artists componentsJoinedByString:@" & "],
song.formattedDuration, song.isFavorite ? @" *" : @"");
}
return 0;
}Night Drive by Lumen & Kael (4:07) *
Test yourself
Which attribute should an NSString * property usually have?
- assign
- weak
- copy
- atomic only
What happens to a weak property when its object is deallocated?
- It keeps pointing to freed memory
- It becomes nil automatically
- The program crashes
- The object is kept alive
Which attribute is the default for an NSInteger property?
- strong
- copy
- assign
- weak