Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the attribute of UITableView's delegate property weak

I found this in UITableView's header file and almost every property is non-arc style though my project is using ARC.

@property (nonatomic, assign)   id <UITableViewDataSource> dataSource;
@property (nonatomic, assign)   id <UITableViewDelegate>   delegate;

Why Apple don't use weak property instead of assign, is it a backward compatibility for non-arc ? If so, why not use __has_feature(objc_arc) to distinguish ARC and non-ARC.

#if __has_feature(objc_arc)
@property (nonatomic, weak)   id <UITableViewDataSource> dataSource;
@property (nonatomic, weak)   id <UITableViewDelegate>   delegate;
#else
@property (nonatomic, assign)   id <UITableViewDataSource> dataSource;
@property (nonatomic, assign)   id <UITableViewDelegate>   delegate;
#endif

I hope delegate is weak so I don't need to set the delegate to nil when the delegate instance is deallocated.

Thanks for your help.

Edit:

I note that __has_feature(objc_arc) is wrong because I can use ARC when my deployment target is 4.3, but then I can't use weak. So the condition should be whether my deployment target is equal to 5.0 or above.

#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_5_0
@property (nonatomic, weak)   id <UITableViewDataSource> dataSource;
@property (nonatomic, weak)   id <UITableViewDelegate>   delegate;
#else
@property (nonatomic, assign)   id <UITableViewDataSource> dataSource;
@property (nonatomic, assign)   id <UITableViewDelegate>   delegate;
#endif
like image 743
KudoCC Avatar asked Dec 03 '14 06:12

KudoCC


1 Answers

Why Apple don't use weak property instead of assign, is it a backward compatibility for non-arc ?

I have done some research and found that, the __weak is synonymous to the “assign” modifier. But only difference is in assign the delegate instance will not set as nil when it is deallocated. You normally use assign modifier for IBOutlets and delegates. Under ARC, this is replaced with __weak. However, there is a caveat. __weak requires you to deploy the app on a runtime that supports zero-ing weak references. This includes, >=(iOS 5 and Lion). Snow Leopard or iOS 4 and older operating systems don’t support zero-ing weak references. This obviously means you cannot use __weak ownership modifiers if you plan to deploy to older operating systems. So Yes, in this sensitive it is a backward compatibility for non-arc.

like image 154
Hussain Shabbir Avatar answered Oct 18 '22 04:10

Hussain Shabbir