90

Whats the difference between this:

@property (nonatomic, weak) id  <SubClassDelegate> delegate; 

and this:

@property (nonatomic, assign) id  <SubClassDelegate> delegate; 

I want to use property for delegates.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Firdous
  • 4,624
  • 13
  • 41
  • 80

1 Answers1

156

The only difference between weak and assign is that if the object a weak property points to is deallocated, then the value of the weak pointer will be set to nil, so that you never run the risk of accessing garbage. If you use assign, that won't happen, so if the object gets deallocated from under you and you try to access it, you will access garbage.

For Objective-C objects, if you're in an environment where you can use weak, then you should use it.

yuji
  • 16,695
  • 4
  • 63
  • 64
  • 16
    Do you know why some of the Cocoa Touch framework classes are still using assign for delegates? For example, the delegate of [UISearchDisplayController](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UISearchDisplayController_Class/Reference/Reference.html#//apple_ref/occ/instp/UISearchDisplayController/delegate) is still assign. Why wasn't it ever updated? – Pwner Feb 07 '14 at 19:26
  • @Pwner looks like it has been deprecated in iOS 8.0 – Stavash Mar 01 '15 at 20:25
  • Here's a non-deprecated example: even `UITableView` has `assign` for its delegate: `@property (nonatomic, assign) id delegate;` – Chris Nolet Mar 20 '15 at 23:59
  • 3
    @ChrisNolet Because probably they are still using MRC (Manual Reference Counting) internally. – Marco Sero Apr 08 '15 at 10:59
  • 3
    As of today, the example of UITableView's delegate is now: @property (nonatomic, weak, nullable) id delegate; So that is no longer a valid example. – sdoowhsoj Dec 06 '17 at 05:00