我正在使用 ARC 编写 iOS 应用程序并面向 iOS 5+。
假设我编写了一个具有委托(delegate)属性的自定义 View 对象。在声明delegate属性时,我将其设为弱引用以避免retain cycle,这样当实际的delegate对象(controller)被销毁时,我的自定义view也会被销毁,如下:
@interface MyCustomView : UIView
@property (nonatomic, weak) id<MyCustomViewDelegate> delegate;
@end
一切都很好。
好的,现在我正在编写 Controller 对象,它引用了两个 View 对象:我的自定义 View 和 Apple 提供的 UIKit View ,它们都声明了委托(delegate)属性,并且 Controller 是两者的委托(delegate)意见。也许它看起来像这样:
@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 来将其中一个或两个委托(delegate)设置为 nil?
我的意思是,据我所知,UIKit View (在本例中为 tableView
)的委托(delegate)属性实际上并未声明为弱引用,而是一个 __unsafe_unretained
引用,用于向后兼容非 ARC 版本的 iOS。所以也许我需要写
- (void)dealloc
{
_tableView.dataSource = nil;
_tableView.delegate = nil;
}
现在,如果我必须覆盖 dealloc,我仍然不必设置 _customView.delegate = nil
,对吧?因为那(由我)声明为弱引用,所以它应该在 MyViewController
销毁时自动设置为 nil。
但另一方面,我不针对非 ARC 版本的 iOS,我也不打算这样做。所以也许我根本不需要重写 dealloc?
最佳答案
将非弱委托(delegate)设置为 nil 通常是个好主意,除非您知道不必这样做。对于 UITableView
和 UIScrollView
,我在以前的 iOS 版本上经历过以下步骤的崩溃(它可能有助于在启用僵尸的情况下运行):
- 滚动速度非常快。
- 按“完成”或“后退”按钮或其他任何方式关闭 VC。
这似乎是因为滚动动画保留了对 View 的引用,所以 View 比 VC 还长。发送滚动事件时崩溃。
我还看到在加载请求时关闭包含 UIWebView
的 VC 后发生崩溃,其中仅将委托(delegate)设置为 nil 是不够的(我认为解决方法是调用 [webView loadRequest:nil]
).
关于ios - 在 ARC 下将委托(delegate)设置为 nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15016348/