我正在使用 ARC 编写 iOS 应用程序并针对 iOS 5+。
假设我编写了一个具有委托属性的自定义视图对象。在声明委托属性时,我将其设为弱引用以避免保留循环,这样当实际委托对象(控制器)被销毁时,我的自定义视图也将被销毁,如下所示:
@interface MyCustomView : UIView
@property (nonatomic, weak) id<MyCustomViewDelegate> delegate;
@end
一切都很好。
好的,现在我正在编写控制器对象,它引用了两个视图对象:我的自定义视图和 Apple 提供的 UIKit 视图,它们都声明了委托属性,控制器是两个视图的委托。也许它看起来像这样:
@interface MyViewController : UIViewController <MyCustomViewDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) MyCustomView *customView;
@property (nonatomic, strong) UITableView *tableView;
@end
@implementation MyViewController
- (void)viewDidLoad
{
self.customView.delegate = self;
self.tableView.dataSource = self;
self.tableView.delegate = self;
}
@end
我的问题是:我是否需要重写 dealloc 以将一个或两个代表设置为零?
我的意思是,据我了解,UIKit 视图的委托属性(在本例中tableView
为 )实际上并未声明为弱引用,而是__unsafe_unretained
引用,以向后兼容非 ARC 版本的 iOS。所以也许我需要写
- (void)dealloc
{
_tableView.dataSource = nil;
_tableView.delegate = nil;
}
现在,如果我必须重写 dealloc,我仍然不必设置_customView.delegate = nil
,对吗?因为那被(我)声明为弱引用,所以它应该在销毁时自动设置为 nil MyViewController
。
但另一方面,我不针对非 ARC 版本的 iOS,也不打算这样做。所以也许我根本不需要覆盖 dealloc?