In Objective-C, which @property attributes do you give a delegate, an NSString, a completion block and an NSInteger, and why?
answer
- ownership plus atomicity per property
- the delegate must not own its owner
- a mutable string passed to the setter
- a block must leave the stack
- atomic is the default, not thread safety
basics
~20 sAll four take nonatomic. The delegate is weak so it never retains its owner; the NSString and the block are copy, snapshotting a mutable string and moving the block off the stack; the NSInteger is assign, its default.
solid answer
~40 sWithout attributes a property is `atomic` and `readwrite`, and under ARC an object property is `strong` while a scalar is `assign`. Most app properties say `nonatomic`, because `atomic` only makes one getter or setter call return a whole value; it does not make the object thread-safe, and it costs time. A delegate is `weak` because the object that sets itself as delegate usually owns the delegating object, and a weak reference is set to `nil` when the delegate deallocates. `assign` on an object pointer means `__unsafe_unretained` and can dangle. An `NSString` is `copy` because the caller may pass an `NSMutableString` and change it later. A block is `copy` because it must leave the stack; under ARC a `strong` block property is copied too, and `copy` documents that. An `NSInteger` takes `assign`.
code
objective-c · 30 lines#import <Foundation/Foundation.h>
@class PPPrintJob;
@protocol PPPrintJobDelegate <NSObject>
- (void)printJobDidFinish:(PPPrintJob *)job;
@end
@interface PPPrintJob : NSObject
// The screen that owns this job is its delegate: weak breaks the loop.
@property (nonatomic, weak) id<PPPrintJobDelegate> delegate;
// A caller may pass an NSMutableString: copy keeps a snapshot.
@property (nonatomic, copy) NSString *caption;
// Blocks are copied off the stack; copy says so in the declaration.
@property (nonatomic, copy) void (^completion)(BOOL success);
// Scalars take assign, which is also their default.
@property (nonatomic, assign) NSInteger copies;
// Read-only to callers; a class extension can redeclare it readwrite.
@property (nonatomic, readonly) BOOL finished;
- (instancetype)initWithCaption:(NSString *)caption;
@end
@implementation PPPrintJob
- (instancetype)initWithCaption:(NSString *)caption {
if ((self = [super init])) {
_caption = [caption copy]; // direct ivar write: copy by hand
}
return self;
}
@endgo deeper
Recall the defaults (atomic, readwrite, strong for objects, assign for scalars) and why a delegate is weak.
Explain what copy protects against with a mutable string, why blocks are declared copy, and why atomic is not thread safety.
Spot the review traps: assign on objects that dangle, copy on a mutable collection, initializers that skip the copy, readonly headers with a readwrite class extension.
Set a house rule for property declarations, such as nonatomic everywhere and copy for value-like classes, and decide how strictly old assign properties get migrated.
## What @property declares An Objective-C `@property` declares a getter and, unless it is `readonly`, a setter, and by default the compiler **synthesizes** both plus a backing instance variable named with a leading underscore. The attributes in parentheses decide how those accessors behave. They fall into a few groups: | Group | Attributes | Default | |---|---|---| | Atomicity | `atomic`, `nonatomic` | `atomic` | | Ownership (objects) | `strong`, `weak`, `copy`, `assign`, `unsafe_unretained`, `retain` | `strong` under ARC | | Ownership (scalars) | `assign` | `assign` | | Access | `readwrite`, `readonly` | `readwrite` | | Nullability | `nullable`, `nonnull`, `null_unspecified` | unspecified | | Naming | `getter=`, `setter=` | derived from the name | Clang's ARC specification maps each ownership attribute to a qualifier on the instance variable: `strong`, `copy` and `retain` mean `__strong`; `weak` means `__weak`; `assign` and `unsafe_unretained` mean `__unsafe_unretained`. Weak references need iOS 5 or later. ## The four properties 1. **The delegate: `nonatomic, weak`.** A print-preview screen typically owns a print job and also sets itself as the job's delegate. If the job held the screen strongly, each would keep the other alive. A `weak` property does not keep the screen alive and is set to `nil` automatically when the screen deallocates, so later messages to the delegate become harmless nil messages. 2. **The caption: `nonatomic, copy`.** The parameter type says `NSString *`, but a caller can pass an `NSMutableString` and append to it afterwards. With `strong`, the job would see those later edits; with `copy`, the setter stores its own copy taken at assignment time. For an immutable string, the copy is cheap. 3. **The completion block: `nonatomic, copy`.** A block literal that captures variables starts life on the stack, and it must be copied to the heap to outlive the method that created it. Apple's blocks guide recommends declaring the property `copy`; it also notes that under ARC the copy happens automatically, so `copy` mainly states the behaviour honestly. 4. **The copy count: `nonatomic, assign`.** An `NSInteger` is a plain value, so there is nothing to own. `assign` is its default, and the compiler rejects `weak` on it with "property with 'weak' attribute must be of object type". ## Why atomic is rarely what you want Properties are `atomic` unless you say otherwise. A synthesized atomic accessor guarantees that a getter running at the same moment as a setter returns a complete value rather than a torn one. It does **not** make the object thread-safe. Apple's guide uses a person whose first and last names are set from one thread while another thread reads both: each read returns a whole string, but the pair can be mismatched. Real thread safety needs a lock or a serial queue around the whole operation. Since atomic accessors are also slower, app code usually writes `nonatomic` everywhere. ## weak, assign and unsafe_unretained - `weak` does not retain and is **zeroed** when the object goes away. - `assign` on an object pointer under ARC is `__unsafe_unretained`: it does not retain and is **not** zeroed, so after the object deallocates the property points at freed memory. The compiler accepts it without a warning, which is why it survives in old code. - `unsafe_unretained` says the same thing explicitly. Apple's guide uses it for the few classes that cannot be referenced weakly. ## Traps in review - **`copy` on a mutable collection.** `@property (nonatomic, copy) NSMutableArray *photos;` stores the result of `copy`, which is an immutable array, so a later `addObject:` raises "unrecognized selector sent to instance". Use `strong`, or expose an immutable `NSArray` and keep the mutable array private. - **Writing the ivar directly.** An initializer that sets `_caption = caption;` bypasses the synthesized setter, so the `copy` never happens; write `_caption = [caption copy];`. - **Custom accessors.** Apple's guide notes that for an `atomic`, `readwrite` property you cannot supply only one accessor and let the compiler synthesize the other; the compiler warns. - **Read-only to callers.** Declare `readonly` in the header and redeclare the property `readwrite` in a class extension in the `.m`, so only the class's own code can set it. - **Boolean getters.** `@property (nonatomic, getter=isFinished) BOOL finished;` keeps the setter as `setFinished:` while the getter reads naturally as `isFinished`. ## A quick checklist For each new property, ask three questions in order: is it an object or a scalar; if an object, does this class own it (`strong`), merely point at it (`weak`), or need a private snapshot of a value-like class such as `NSString`, `NSArray` or a block (`copy`); and can `nil` be a real value, which belongs in a `nullable` attribute when the header uses nullability annotations.
- Why does `@property (nonatomic, copy) NSMutableArray *photos;` crash on `addObject:`?The synthesized setter stores `[value copy]`, and `copy` on a mutable array returns an immutable one. The property's type still says `NSMutableArray`, so the compiler accepts `[self.photos addObject:...]`, but at run time the immutable array raises "unrecognized selector sent to instance". Declare it `strong`, or write a setter that stores `mutableCopy`.
- Does making every property of a print order atomic make the order thread-safe?No. Atomic accessors only guarantee that one get or set returns or stores a whole value. Two properties read from another thread can still be a mismatched pair, and a read-modify-write such as incrementing `copies` can still lose updates. Guard the whole operation with a lock or a serial queue instead.
- When do you still meet `assign` or `unsafe_unretained` on an object property, and what is the risk?In code written before weak references existed, and for the few classes that cannot be referenced weakly. Both mean a non-owning pointer that is not zeroed, so a message sent after the object deallocates goes to freed memory and crashes unpredictably. Convert them to `weak` wherever the class allows it.
- Delegates should be strong so they are not deallocated too early.
- assign is fine for a delegate object under ARC.
- Atomic properties make the whole object thread-safe.
- copy on an NSString property is pointless because strong behaves the same.
- Under ARC a strong block property leaves the block on the stack.
- weak on an NSInteger property avoids retain cycles.