执行选择器延迟后不起作用
我在 uiview 子类中使用以下方法:
[self performSelector:@selector(timeout) withObject:nil afterDelay:20];
该方法按预期在 20 秒后调用。 在另一种方法中,我尝试使用以下代码取消执行请求:
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(timeout) object:nil];
我也尝试过
[NSRunLoop cancelPreviousPerformRequestsWithTarget:self selector:@selector(timeout) object:nil];
这两条消息都没有带来预期的结果,并且仍然调用超时方法。 谁能解释一下我做错了什么以及如何以正确的方式做到这一点?
来自奥地利的欢呼 马丁
i am using the following method in a uiview subclass:
[self performSelector:@selector(timeout) withObject:nil afterDelay:20];
The method is called after 20 seconds as expected.
In another method i try to cancel the perform request using the following code:
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(timeout) object:nil];
i've also tried
[NSRunLoop cancelPreviousPerformRequestsWithTarget:self selector:@selector(timeout) object:nil];
both messages don't bring the expected result an the timeout method is still called.
can anybody explain me what i am doing wrong and how to do it the right way ?
cheers from austria
martin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
两点
1. 两个
self
是同一个对象吗?2.
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(timeout) object:nil];
是否在您调用[self PerformSelector:@selector(timeout) withObject:nil 的同一线程上执行afterDelay:20];
?检查这两个问题。
Two points
1. Are both
self
same object??2. Is
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(timeout) object:nil];
performed on same thread on which you called[self performSelector:@selector(timeout) withObject:nil afterDelay:20];
?Check these two problems.
使用作为实例变量存储在类中的 NSTimer。当你想取消执行时,使定时器失效并销毁。
在您的@interface中:
在您的@implementation中:
然后,如果发生某种情况并且不应再调用超时方法:
Use an NSTimer stored as an instance variable in your class. When you want to cancel the perform, invalidate and destroy the timer.
In your @interface:
In your @implementation:
Then, if some condition happens and the timeout method should no longer be called:
试试这个:
Try this:
您可以通过两种方式做到这一点:
您可以使用此方法来删除所有排队的内容
[NSObject cancelPreviousPerformRequestsWithTarget:self];
您可以单独删除每一个
[NSObject cancelPreviousPerformRequestsWithTarget:self
选择器:@selector(超时)
object:nil];
You can do that with 2 ways :
You could use this which would remove all queued
[NSObject cancelPreviousPerformRequestsWithTarget:self];
you can remove each one individually
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(timeout)
object:nil];