延迟通话,有可能取消?

时间:2008-12-03 14:24:46

标签: objective-c cocoa

如何触发延迟,假设我想在3秒内调用一个方法(一次),如果需要,我该如何取消该调用呢?

3 个答案:

答案 0 :(得分:7)

您还可以使用-[NSObject performSelector:awithObject:afterDelay:]+[NSObject cancelPreviousPerformRequestsWithTarget:selector:object]

答案 1 :(得分:3)

使用 NSTimer 。使用此选项可在三秒钟内设置对方法的调用。它只会被调用一次:

   [NSTimer scheduledTimerWithTimeInterval: 3
                                    target: self
                                  selector: @selector(method:)
                                  userInfo: nil
                                   repeats: NO];

方法需要如下所示:

- (void) method: (NSTimer*) theTimer;

您可以使用 userInfo (在上例中设置为 nil )将参数传递给方法。它可以在方法中作为 [theTimer userInfo]

进行访问

使用NSTimer上的 invalidate 方法取消它。

答案 2 :(得分:1)

标题中的

..

NSTimer *timer;

当您想要设置..

timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(yourMethod:) userInfo:nil repeats:NO];

当你想要取消..

[timer invalidate];
相关问题