NSOperation 子类中的 NSTimer
亲爱的社区。 我尝试
@interface GetExternalInfo : NSOperation {
NSTimer *keepAliveTimerMain;
@property (nonatomic,retain) NSTimer *keepAliveTimerMain;
设置 NSTimer: .m:
@synthesize keepAliveTimerMain
-(void) main;
{
self.keepAliveTimerMain = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(keepAlive:) userInfo:nil repeats:YES];
[keepAliveTimerMain fire];
[[NSRunLoop currentRunLoop] addTimer:self.keepAliveTimerMain forMode: NSDefaultRunLoopMode];
BOOL timerState = [keepAliveTimerMain isValid];
NSLog(@"STAT:Timer Validity is: %@", timerState?@"YES":@"NO");
- (void)keepAlive:(NSTimer *)theTimer
{
BOOL currentState = [self isCancelled];
NSLog(@"STAT:cancelled state is %@.\n",currentState?@"YES":@"NO");
}
在日志中
2011-02-02 18:58:31.041 雪[54705:5d07] STAT:取消状态 是否。 2011-02-02 18:58:31.042 雪[54705:5d07] STAT:计时器有效性 是:是
我只看到一次。每 5 秒不再重复尝试 对于这种情况有什么意见吗? GC 已启用。
Dear community.
I try to setup NSTimer:
@interface GetExternalInfo : NSOperation {
NSTimer *keepAliveTimerMain;
@property (nonatomic,retain) NSTimer *keepAliveTimerMain;
.m:
@synthesize keepAliveTimerMain
-(void) main;
{
self.keepAliveTimerMain = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(keepAlive:) userInfo:nil repeats:YES];
[keepAliveTimerMain fire];
[[NSRunLoop currentRunLoop] addTimer:self.keepAliveTimerMain forMode: NSDefaultRunLoopMode];
BOOL timerState = [keepAliveTimerMain isValid];
NSLog(@"STAT:Timer Validity is: %@", timerState?@"YES":@"NO");
- (void)keepAlive:(NSTimer *)theTimer
{
BOOL currentState = [self isCancelled];
NSLog(@"STAT:cancelled state is %@.\n",currentState?@"YES":@"NO");
}
In Logs
2011-02-02 18:58:31.041
snow[54705:5d07] STAT:cancelled state
is NO. 2011-02-02 18:58:31.042
snow[54705:5d07] STAT:Timer Validity
is: YES
i see this only once. No next repeat attempts every 5 seconds
any opinions in this case? GC is enabled.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当前线程中有runloop吗?计时器需要一个运行循环才能触发。我注意到您手动调用
-fire
这解释了为什么调用-keepAlive
,但这实际上并没有启动计时器。Do you have a runloop in the current thread? The timer needs a runloop to be able to fire. I notice you call
-fire
manually which explains why-keepAlive
is called, but this doesn't actually start the timer.您需要将计时器添加到运行循环中,例如
[[NSRunLoop currentRunLoop] addTimer:keepAliveTimerMain forMode: NSDefaultRunLoopMode];
。编辑:您发布的代码显示您在将计时器添加到运行循环之前手动触发。这将触发并使计时器无效,因此您实际上是在尝试在运行循环上安排一个无效的计时器。这就是为什么你只看到一次 NSLog 消息。
You need to add your timer to a run loop, something like
[[NSRunLoop currentRunLoop] addTimer:keepAliveTimerMain forMode: NSDefaultRunLoopMode];
.EDIT: The code you posted shows that you manually fire the timer before adding it to the runloop. This will fire and invalidate the timer, so you are actually trying to schedule an invalid timer on the runloop. That is why you only see the NSLog message once.