NSTimer未失效

时间:2011-10-11 04:47:10

标签: objective-c ios nstimer invalidation

我正在为RKObjectManager实现超时。我的代码段如下:

-(void)getObjects
{
    RKObjectManager *sharedManager = [RKObjectManager sharedManager];

    [self showLoading];
    [sharedManager loadObjectsAtResourcePath:self.resourcePath delegate:self];

    // Setting timeout here. goto failure 
    self.nTimer = [NSTimer scheduledTimerWithTimeInterval:TIMEOUT_INTERVAL target:self selector:@selector(didEncounterError) userInfo:nil repeats:NO];
}

- (void) didEncounterError
{    
    [self hideLoading];
    [self standardErrorHandling];

    //invalidate timer, this is done to ensure that if error occurs before timer expiry time, the error will not show again when timer is up (ISSUE HERE)
    [self.nTimer invalidate];
}

- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects 
{
    ....
    //invalidate timer if load is successful (no issue here)
    [self.nTimer invalidate];
}


- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error 
{
    ....
    //trigger encounter error method
    [self didEncounterError];
}

在上面的实现中,我总是在“遇到错误”方法中使计时器无效。这是为了缓解在计时器到期之前发生错误的情况。我希望在这种情况下使计时器无效,以防止错误消息再次弹出。

但是,在错误发生后(在计时器到期之前),我仍然第二次收到错误消息。似乎“遇到错误”方法中的失效不起作用。有关我的代码有什么问题的建议吗?

1 个答案:

答案 0 :(得分:7)

计时器失效应该发生在调度它的线程上,在上面的情况下,它会在另一个线程上调用(回调)。你有没有一种方法来执行这种失效,并在你的回调方法中使用'performSelectorOnMainThread'调用该方法?