gpt4 book ai didi

objective-c - NSTimer代码永远执行

转载 作者:行者123 更新时间:2023-12-01 19:23:18 24 4
gpt4 key购买 nike

这是我的代码。我希望计时器在启动后的5秒钟内停止,但事实并非如此。这是怎么了

-(void)loadView
{
NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate];



NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.0
target:self
selector:@selector(targetMethod:)
userInfo:nil
repeats:YES];
if([NSDate timeIntervalSinceReferenceDate] - startTime >= 5) {
[timer invalidate];
}

}

-(void)targetMethod:(NSTimer *)timer {


NSLog(@"bla");
}

最佳答案

默认情况下,NSDate的timeIntervalSinceReferenceDate返回2001年1月1日。相减相同的值将始终为0。

苹果的文档:
https://developer.apple.com/library/mac/ipad/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html

这是一个主意:
在您的.h中

@interface MyClass : NSObject

@property (nonatomic, retain) NSTimer *timer;

- (void)targetMethod:(NSTimer *)timer;
- (void)cancelTimer;

@end

在您的.m中
@implementation MyClass

@synthesize timer;

-(void)loadView
{
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.0
target:self
selector:@selector(targetMethod:)
userInfo:nil
repeats:YES];
[self performSelector:@selector(cancelTimer) withObject:nil afterDelay:5.0];
}

-(void)cancelTimer {
[self.timer invalidate];
}

-(void)targetMethod:(NSTimer *)timer {
NSLog(@"bla");
}

关于objective-c - NSTimer代码永远执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9140759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com