PerformSelector: afterDelay: 不保留目标?

发布于 2024-12-26 20:08:56 字数 383 浏览 5 评论 0原文

我有一个类,它使用 NSURLConnection 打开与服务器的长时间运行的连接。当连接关闭时,无论是在connectionDidFinishLoading:还是connection:didFailWithError:中,我想等待15秒,然后重试连接。

目前我正在使用 [self PerformSelector:@selector(restartConection) withObject:nil afterDelay:15.0];,但这会导致不良情况,即当对象被其创建者释放时, PerformSelector 和 NSURLConnections 永远保留“self”,并且它永远不会被释放。

我怎样才能做到这一点而不永久保留该对象?任何帮助将不胜感激。

谢谢,-亚历克

I've got a class which uses NSURLConnection to open a long-running connection to a server. When the connection's closed, either in connectionDidFinishLoading: or connection:didFailWithError:, I want to wait 15 seconds then retry the connection.

At the moment I'm using [self performSelector:@selector(restartConection) withObject:nil afterDelay:15.0];, but this leads to the undesired situation that when the object is released by its creator, the performSelector and NSURLConnections perpetually retain 'self', and it never gets deallocated.

How can I do this without perpetually retaining the object? Any help'd be much appreciated.

Thanks, -Alec

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

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

发布评论

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

评论(2

花辞树 2025-01-02 20:08:56

发送

[NSTimer cancelPreviousPerformRequestsWithTarget: object];

我认为您唯一的选择是在释放对象之前的某个时刻 。如果计时器尚未安排,则这是一个空操作,但在性能方面并不是免费的。

I think your only option is to send

[NSTimer cancelPreviousPerformRequestsWithTarget: object];

at some point, probably, before releasing the object. If the timer hasn't been scheduled, this is a no-op, but is not free performance-wise.

妖妓 2025-01-02 20:08:56

您无法避免保留该对象。保留它是为了避免在下一个主循环中运行时在已释放对象上调用选择器时发生丑陋的崩溃。

如果您确实坚持立即释放对象而不等待延迟选择器,我建议您创建一个单独的代理类。假设您的类名为 A,创建代理类 B,它将对您的类 A 有一个弱引用(即 __weak A* a) 和 restartConnection 选择器将检查弱引用是否有效。如果是这样,它将在您的 A 对象上调用 restartConnection。然后,当然,在 BrestartConnection 上执行延迟选择器,

但首先,我真的建议您重新评估是否真的无法忍受保留。

You cannot avoid retaining the object. It is retained in order to save you from ugly crashes when in the next main loop cycle the runtime is going to call your selector on the released object.

If you really insist on having your object released immediately without waiting for your delayed selector, I would suggest you to create a separate proxy class. Say your class is called A, create proxy class B which will have a weak reference to your class A (i.e. __weak A* a) and restartConnection selector which will check if the weak reference is valid. If so it would invoke restartConnection on your A object. Then, do, of course, a delayed selector on B's restartConnection

But first of all, I would really suggest that you reevaluate whether you really cannot live with the retain.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文