PerformSelector: afterDelay: 不保留目标?
我有一个类,它使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
发送
我认为您唯一的选择是在释放对象之前的某个时刻 。如果计时器尚未安排,则这是一个空操作,但在性能方面并不是免费的。
I think your only option is to send
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.
您无法避免保留该对象。保留它是为了避免在下一个主循环中运行时在已释放对象上调用选择器时发生丑陋的崩溃。
如果您确实坚持立即释放对象而不等待延迟选择器,我建议您创建一个单独的代理类。假设您的类名为
A
,创建代理类B
,它将对您的类A
有一个弱引用(即__weak A* a
) 和restartConnection
选择器将检查弱引用是否有效。如果是这样,它将在您的A
对象上调用restartConnection
。然后,当然,在B
的restartConnection
上执行延迟选择器,但首先,我真的建议您重新评估是否真的无法忍受保留。
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 classB
which will have a weak reference to your classA
(i.e.__weak A* a
) andrestartConnection
selector which will check if the weak reference is valid. If so it would invokerestartConnection
on yourA
object. Then, do, of course, a delayed selector onB
'srestartConnection
But first of all, I would really suggest that you reevaluate whether you really cannot live with the retain.