iOS:如何处理已释放的委托(delegate)

标签 ios delegates

我有一个对象作为我的 View Controller 和我的网络服务之间的连接层。该对象接受一个委托(delegate),并在数据从服务器返回时通知该委托(delegate)。我遇到了一个问题,即在 http 请求运行时委托(delegate)被释放。当请求返回时,我的对象尝试调用委托(delegate)上的方法,并且应用程序崩溃。

处理这个问题的最佳方法是什么。我在几个地方读到,你不应该保留你的委托(delegate),因为他们经常也保留该对象,从而导致循环依赖。因此,如果我无法保留我的委托(delegate),在调用它的方法之前如何检查它是否已被释放?

@property (nonatomic, assign) NSObject<ServerConnectionDelegate>* delegate;

最佳答案

如果委托(delegate)的生命周期比工作对象的生命周期长,通常您应该使用委托(delegate)模式。 (抱歉,不确定这里的术语是否正确)。

您有多种解决方法:

  • 作为解决方法,您可以在对象的 dealloc 方法中将连接委托(delegate)设置为 nil。
  • 如果需要数据(可能供以后使用),您可以使用 NSNotification 来通知委托(delegate)任何连接事件,而不是委托(delegate)模式。
  • 正如 Jack 在评论中建议的那样,您可以使您的委托(delegate)成为连接的弱属性 - 如果您的项目使用 ARC,这可能是最好的解决方案

关于iOS:如何处理已释放的委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12733742/

相关文章:

iphone - 通过目的地的 Google map KML 输出或带有 MKMapkit 的 Google Direction API

ios - 使用终端命令 'open -n -a "iOS Simulator"' 运行多个 iOS Simulator.app

iphone - 在 UIView 上设置 Uibutton 随机位置

ios - 使用 Interface Builder 为 UITabBarViewController 设置委托(delegate)时应用程序崩溃

c# - 可以将 Action 隐式分配给 void 委托(delegate)吗?

ios - 使 UITextView 变小的约束

iphone - iOS 每天在特定时间触发本地通知

c# - 将各种参数传递给委托(delegate)

c# - C# : "An object reference is required for the non-static field, method, or property" 错误

objective-c - UITableView 委托(delegate)方法被调用了两次