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.

1 Answer 1

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.

5
  • 16
    Do you know why some of the Cocoa Touch framework classes are still using assign for delegates? For example, the delegate of UISearchDisplayController is still assign. Why wasn't it ever updated?
    – Pwner
    Feb 7, 2014 at 19:26
  • @Pwner looks like it has been deprecated in iOS 8.0
    – Stavash
    Mar 1, 2015 at 20:25
  • Here's a non-deprecated example: even UITableView has assign for its delegate: @property (nonatomic, assign) id <UITableViewDelegate> delegate; Mar 20, 2015 at 23:59
  • 3
    @ChrisNolet Because probably they are still using MRC (Manual Reference Counting) internally.
    – Marco Sero
    Apr 8, 2015 at 10:59
  • 3
    As of today, the example of UITableView's delegate is now: @property (nonatomic, weak, nullable) id <UITableViewDelegate> delegate; So that is no longer a valid example.
    – sdoowhsoj
    Dec 6, 2017 at 5:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.