Explain Property Attributes in Objective C

1. assign
  • It Does:
    • Simply assigns the value to the instance variable.
    • Does not retain the object (does not increase the retain count).
  • When to use:
    • Primitive types (like int, float, BOOL) because they don’t require memory management.
@property (nonatomic, assign) NSInteger number;

Difficulty: Using assign for objects can cause dangling pointers if the assigned object is deallocated.

@property (nonatomic, assign) NSString *subtitle;
/* it not valid */

If subtitle is deallocated elsewhere, this property will point to invalid memory, leading to a crash.

2. strong
  • It does:
    • The property owns the object.
    • It is known as retail in MRC.
    • Increases the retain count.
    • The object will stay in memory as long as you have a strong reference.
@property (nonatomic, strong) NSString *firstName;

ARC Behavior:

  • When a new value is assigned:
    1. New object is retained.
    2. Old object is released.

Difficulty: Can cause retain cycles if two objects strongly reference each other (common in delegate patterns or blocks).

3. weak
  • It does:
    • Does not retain the object (retain count is not increased).
    • If the object is deallocated, the pointer is automatically set to nil (only under ARC).
@property (nonatomic, weak) id<NewDelegate> delegate;

When to use:

  • To avoid retain cycles, commonly for delegate properties.

Example of avoiding retain cycle:

@interface Child : NSObject
@property (nonatomic, weak) Parent *parent;
@end

Here, if parent has a strong reference to child and child has a weak reference to parent, memory will be released properly.

4. copy
  • What it does:
    • Creates a new copy of the object.
    • Useful when you want your property to be immutable, even if a mutable object is assigned.
  • Typical use:
@property (nonatomic, copy) NSString *newName;

Why use copy with NSString:

NSMutableString *mutable = [NSMutableString stringWithString:@"Hello world"];
obj.newName = mutable;
[mutable appendString:@"one"];

NSLog(@"%@", obj.newName);

With strong: “Hello World one” → because both point to the same mutable object.

With copy: “Hello world” → because property makes its own immutable copy.

Difficulty:

  • Copying a large object has a performance cost.
  • Avoid unnecessary copy for objects that are always immutable (like NSArray literals).