objective-c中使用NSTimer如下语句为何没有输出?

NSInteger _count;
NSTimer* _timer;

  • (void)tel{ NSLog(@"正在打第%ld个电话",_count++); if(_count>10){ NSLog(@"定时器关闭"); [_timer invalidate]; } }
  • (void)timerTest{ _timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(tel) userInfo:nil repeats:YES]; } main函数中创建对象xxx,然后调用[xxx timerTest];为何什么输出都没有? 我是在command line tool中写的,不是ios项目,不知道是不是这个原因

timer需要有消息循环。UI线程等调用

NSTimer在后台运行
更多 0
objective-c基础
这段代码可以放在- (void)applicationWillResignActive:(UIApplication )application或者- (void)applicationDidEnterBackground:(UIApplication )application 中,当然,当程序重新被激活的时候,需要将timer invalidate掉。
UIApplication *app = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid) {
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    testTimer = [NSTimer scheduledTimerWithTimeInterval:(0.01) target:self selector:@selector(doSomeTest) userInfo:nil repeats:YES];
    [testTimer fire];
    [[NSRunLoop currentRunLoop] addTimer:testTimer forMode:NSRunLoopCommonModes];

    [[NSRunLoop currentRunLoop] run];

    dispatch_async(dispatch_get_main_queue(), ^{
        if (bgTask != UIBackgroundTaskInvalid) {
            [app endBackgroundTask:bgTask];
            bgTask = UIBackgroundTaskInvalid;
        }
    });

});
//该片段来自于http://outofmemory.cn

你看你是不是在主线程添加的timer 如果是异步线程的话,不能添加到currentRunloop 要添加到mainRunloop