如何在块功能内创建定时器时触发定时器?

时间:2013-12-13 11:40:46

标签: ios objective-c objective-c-blocks

@interface Taxi_MainViewController : Taxi_BaseNavViewController
{
  __block NSTimer *timer_;
}



  [Taxi_do_order psg_place_orderWithMemberId:strMemberId_ orderStatus:K_orderStatus_open andCLLocationCoord:location.coordinate callback:^(NSInteger iOrderId){
        [Taxi_StatusView dismiss];
        if (iOrderId >=0)
        {
            isOrderExist = YES;
            [weakSelf_ showWaittingDriverAcceptView];
            timer_ =   [NSTimer scheduledTimerWithTimeInterval:2.0
                                                               target:weakSelf_
                                                             selector:@selector(actListen:)
                                                             userInfo:nil
                                                              repeats:YES];
        }else
            [weakSelf_ hideWaittingDriverAcceptView];
    }faile:^(){
        [Taxi_StatusView showLostNetWork];
    }];

当我调用[timer_ invalidate]时,timer_ = nil;在其他方法中,定时器功能仍然每2秒调用一次。

1 个答案:

答案 0 :(得分:1)

在您的情况下,变量timer_永远不会保留,并且您将丢失指针 在结束块范围。使用属性,您有保留/释放机制。

试试这个:

@interface Taxi_MainViewController : Taxi_BaseNavViewController
{

}

@property (nonatomic,retain) NSTimer* timer;

@end



[Taxi_do_order psg_place_orderWithMemberId:strMemberId_ orderStatus:K_orderStatus_open andCLLocationCoord:location.coordinate callback:^(NSInteger iOrderId){
        [Taxi_StatusView dismiss];
        if (iOrderId >=0)
        {
            isOrderExist = YES;
            [weakSelf_ showWaittingDriverAcceptView];
            self.timer =   [NSTimer scheduledTimerWithTimeInterval:2.0
                                                               target:weakSelf_
                                                             selector:@selector(actListen:)
                                                             userInfo:nil
                                                              repeats:YES];
        }else
            [weakSelf_ hideWaittingDriverAcceptView];
    }faile:^(){
        [Taxi_StatusView showLostNetWork];
    }];