Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 38 ยท Memory Management and ARC

Strong, Weak, Copy and Property Attributes

Learn @property attributes in Objective-C - strong, weak, copy, assign, atomic, nonatomic, readonly - when to use each, why NSString needs copy, and how weak references zero out.

A property declaration is a short promise about ownership. When you write @property (nonatomic, strong) NSString *title; you are telling the compiler how the setter should treat the incoming object: keep it, copy it, or merely look at it. Pick the wrong attribute and you get either a leak, a crash, or data that changes behind your back.

This lesson covers every attribute you will meet, with a rule for each one and a C model of what a zeroing weak reference does.

The attribute families

Property attributes fall into groups, and you choose one from each:

Group Choices Default
Memory strong, weak, copy, assign, unsafe_unretained strong for objects, assign for primitives
Atomicity atomic, nonatomic atomic
Writability readwrite, readonly readwrite
Method names getter=, setter= foo / setFoo:
OBJECTIVEC
@interface Person : NSObject
@property (nonatomic, copy)     NSString *name;       // owns a private copy
@property (nonatomic, strong)   NSArray  *friends;    // owns the array
@property (nonatomic, weak)     id<PersonDelegate> delegate; // does not own
@property (nonatomic, assign)   NSInteger age;        // primitive: plain assign
@property (nonatomic, readonly) NSString *identifier; // no public setter
@property (nonatomic, getter=isActive) BOOL active;   // custom getter name
@end

strong

The setter retains the new value and releases the old one. Use strong for the objects your class is responsible for: subviews, models, child objects, arrays you created.

weak

The setter stores the pointer without retaining. When the object is deallocated, the runtime sets every weak pointer to it to nil. Use weak for back references: delegates, parent pointers, and anything that would otherwise create a retain cycle. Messages sent to nil do nothing, so a vanished delegate is simply ignored.

copy

The setter stores [value copy]. This is the right choice for classes that have mutable subclasses: NSString, NSArray, NSDictionary, NSSet, NSData, and for blocks. Without it, a caller could pass an NSMutableString, keep a reference, and change your string later.

OBJECTIVEC
NSMutableString *text = [NSMutableString stringWithString:@"draft"];
person.name = text;          // with `strong` this stores the same mutable object
[text appendString:@" 2"];   // person.name is now "draft 2": surprise!
// with `copy`, person.name stays "draft"

For immutable inputs copy is nearly free: copying an immutable NSString just retains it.

assign and unsafe_unretained

assign is a plain pointer assignment, correct for int, BOOL, CGFloat, structs and enums. unsafe_unretained does the same for object pointers: no retain and no zeroing. It exists for rare cases (old OS versions, performance) and leaves a dangling pointer if the object dies. Prefer weak.

atomic and nonatomic

atomic (the default) makes the getter and setter thread-safe for that single access by locking. It does not make your class thread-safe, since two related properties can still be inconsistent. Most iOS and macOS code writes nonatomic for speed and uses queues or locks at a higher level.

readonly and class extensions

A public readonly property can be made writable inside the implementation with a class extension. Outside code can read it, only the class can change it.

OBJECTIVEC
// Account.h
@interface Account : NSObject
@property (nonatomic, readonly) double balance;
@end

// Account.m
@interface Account ()
@property (nonatomic, readwrite) double balance;  // private writable redeclaration
@end

See categories and extensions for more on class extensions.

How a zeroing weak reference works

The runtime keeps a side table of all weak pointers registered against each object. When the object is deallocated, it walks that table and writes nil to each pointer. The C model below does the same with an array of registered slots.

C Stand-in: weak references that become NULL

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

An unsafe_unretained pointer would skip the weak_assign registration. After node_dealloc it would still hold the old address, and using it would be undefined behavior.

Copy semantics in practice

Here is the mutable-string trap as a runnable stand-in with a "property setter" that either keeps the pointer (strong) or duplicates the text (copy).

C Stand-in: strong vs copy setter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Quick decision guide

  • Object you are responsible for: strong.
  • Delegate, data source, parent: weak.
  • String, array, dictionary, set, block: copy.
  • Number, boolean, struct, enum: assign.
  • Property that only the class should set: readonly plus a private readwrite redeclaration.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which attribute should a delegate property normally use?

    A delegate usually owns its owner indirectly, so a strong reference would form a retain cycle.
  2. 2. Why is copy recommended for an NSString property?

    copy snapshots mutable input; for immutable strings it costs almost nothing.
  3. 3. What is the difference between weak and unsafe_unretained?

    Both avoid ownership, but only weak is zeroed automatically.
  4. 4. What does atomic guarantee?

    It protects the single access, not multi-step operations or related properties.
  5. 5. Which attribute fits an NSInteger property?

    Primitives are not objects, so there is nothing to retain.

Summary

  • strong owns, weak observes and zeroes, copy snapshots, assign is for primitives.
  • Use copy for strings, collections and blocks.
  • atomic locks one access; it is not full thread safety.
  • Make a property readonly publicly and redeclare it readwrite in a class extension.

Next: Retain Cycles and Autorelease Pools