为什么保留委托是错误的,所有替代方案是什么......?

发布于 2024-09-03 03:48:49 字数 253 浏览 2 评论 0原文

我有一个问题,假设A和B是2个视图控制器,从A用户推送到B视图控制器,在B中,用户通过创建对象C(它是NSObject类)开始一些下载,并将B设置为C的委托(分配),现在用户想要返回到 A,然后释放 B 调用对象释放,C 委托无法回拨(崩溃)。我想要获得呼叫并允许用户移动到其他视图控制器,这就是我在 C 类中保留委托的方式,但是保留代表是错误的......

what are all solutions ...

提前致谢。

I have one problem let assume A and B are 2 view controller from A user push to B view controller,In B user starts some download by creating object C(which is NSObject class) and sets B as delegate to C(assign),now user want go back to A then dealloc of B calls object releases, C delegate fails to give call back(crashes).I want to get call and allow user to move to other view controller thats way i am retain the delegate in C class but retain of delegate is wrong ...

what are all solutions ...

Thanks in Advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

通知家属抬走 2024-09-10 03:48:49

我看到两个选项:

  1. 您不需要下载的数据。解决办法:将delegate设置为nil。
  2. 你需要数据。解决方案:您要么设置一个存在的新委托,要么该委托应​​确保它将存在(通过成为单例)

I see two options:

  1. You do not need the downloaded data. Solution: set the delegate to nil.
  2. You need the data. Solution: You either set a new delegate that exists, or the delegate should make sure it will be around (f.e. by being a singleton)
陈甜 2024-09-10 03:48:49

发生这种情况是因为您的架构中存在问题:您将后台下载的全局任务分配给可能位于内存中也可能不在内存中的视图控制器。

如果您希望无论 B 是否存在都能够继续下载,那么:

  1. 创建一个类“下载器”来负责下载文件(我相信您在示例中将其称为 C)。
  2. 这样的类应该有一个“弱”类型的委托,这样如果原始委托消失,应用程序就不会崩溃(注意:这仅在您使用 ARC 时可用)。如果您需要全局监控下载进度,请切换到 NSNotification 而不是 delegate,以便多个对象可以同时监控。
  3. 在其他地方初始化 C 的实例:在 A 中或之前。
  4. 通过创建自定义 init 方法或 @property 将 C 的实例注入 B 中。

That happens because of an issue in your architecture: you're assigning the global task of background downloading to a view controller that may or may not be in memory.

If you want to be able to continue the download regardless of the presence of B, then:

  1. Create a class "downloader" that takes care of downloading files (I believe you call it C in your example).
  2. Such class should have a delegate of type "weak" so that if the original delegate goes away, the app won't crash (NOTE: this is only available if you use ARC). If you need to globally monitor the progress of your download, switch to NSNotification instead of delegate so that multiple object can monitor at the same time.
  3. Initialize an instance of C somewhere else: either in A or before that.
  4. Inject the instance of C into B so that B by creating a custom init method or a @property.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文