1

I found something that I can't understand in UICollectionView header file. I found that the delegate has an assign property

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

This question is only for my basic understanding as the rule says the delegate should have a weak property. And according to my personal knowledge, assign won't reference count the delegate object but it will surely still have a reference to a garbage value if the object is deallocated.

How can I understand this piece of code?

halfer
  • 19,824
  • 17
  • 99
  • 186
Ashraf Tawfeeq
  • 3,036
  • 1
  • 20
  • 34

1 Answers1

3

strong and weak were introduced alongside Automatic Reference Counting (ARC). UIKit moved to ARC with iOS 9, and if you look at the iOS 9 header (using Xcode 7) you will see that this property is now weak.

You are right: with the property as assign (which is equivalent to unsafe_unretained), if the delegate is deallocated while the collection view is alive, the collection view’s delegate property will point to where the deallocated object used to be and probably cause a crash when it is referenced. This is not usually a problem because the delegate is often the view controller owning the collection view so usually outlives the view. However, this is not a guarantee, which is why you should set assign delegates that point to you to nil in your dealloc.

Relevant Stack Overflow questions:

Community
  • 1
  • 1
Douglas Hill
  • 1,537
  • 10
  • 14