如果学会了如果委托的寿命比对象短,应该从对象中删除委托的困难方式。但是如果你没有对象的引用,你如何做到这一点?从未引用的对象上删除dealloc上的委托
在我的iPhone应用程序中,我有一个视图控制器vc
,它执行异步活动并显示为模态视图。取消按钮取消模态视图。如果发生错误,则显示UIAlertView alert
。如果用户点击确定,alert
和模态视图都会消失。因此vc
被设置为 作为alert
的代表并且实施alertView:didDismissWithButtonIndex:
。例如:
// UIViewController vc
...
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Error"
message:@"Something went wrong"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
self.alertView = alert; // needed to unset alertView.delegate in dealloc
[alert show];
[alert release];
...
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
[self dismissModalViewControllerAnimated:YES];
}
}
通常,警报视图会阻止所有输入。不幸的是,它在某些边缘情况下没有这样做。 如果用户在警报视图出现之前触摸取消按钮,并在出现警报视图后触摸,视图将被取消,但不取消警报。 vc
被取消分配,并且如果用户在警报上点击“ok”,则应用程序崩溃,因为消息已发送到已发布的对象。
我通过将alert
分配给vc
属性解决了这个问题,所以我可以设置alert.delegate
在dealloc中为零。我觉得这个解决方案不是很优雅,因为我不需要参考警报。
有没有更好的方法?
编辑:添加在斜体为澄清
我尝试设置userInteractionEnabled = NO,但在取消按钮的触摸停止仍在处理。我可能不得不参考警报方式。 –