开发者

NSTimer in NSOperation subclass

开发者 https://www.devze.com 2023-02-08 08:11 出处:网络
Dear community. I try to setup NSTimer开发者_如何学JAVA: @interface GetExternalInfo : NSOperation {

Dear community. I try to setup NSTimer开发者_如何学JAVA:

@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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消