我可以在另一个NStimer中使用NStimer吗?

时间:2016-04-27 07:58:48

标签: ios objective-c cocoa-touch nstimer

我创建了一个NSTimer

timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(sendImage) userInfo:nil repeats:YES];

在方法sendImage中,我创建了另一个NSTimer timer2。代码如下:

- (void)sendImage
  {
     for(int i = 0;i < 50 ; i++)
     {
         NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
         [dict setObject:socket forKey:@"socket"];//parameter which deliver to the method`sendPieceOfImage`
         [dict setObject:pData forKey:@"pData"];
         timer2 = [NSTimer scheduledTimerWithTimeInterval:0.002f target:self selector:@selector(sendPieceOfImage:) userInfo:dict repeats:NO];
     }
  }

但它没有用。我想知道NSTimer可以机械地申请吗?如果它不可行,我可以在sendImage中做些什么。我希望for()中的每个循环都能以间隔运行。

1 个答案:

答案 0 :(得分:0)

你的问题的答案是肯定的。可以在另一个的触发回调中安排一个计时器。考虑一下:

dispatch_async(dispatch_get_main_queue(), ^{
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timer1Event:) userInfo:nil repeats:YES];
});

- (void)timer1Event:(NSTimer*)timer {
    NSLog(@"timer1Event");
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timer2Event:) userInfo:nil repeats:NO];
}

- (void)timer2Event:(NSTimer*)timer {
    NSLog(@"timer2Event");
}

即使问题没有完全描述,我也会尝试猜测根本原因在于第一个计时器是如何安排的。

你需要使用不同的设置RunLoop的线程。主线是合适的。

dispatch_async(dispatch_get_main_queue(), ^{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(sendImage) userInfo:nil repeats:YES];
});

如果您不想加载主线程,请考虑以下事项:

你需要自己的线程:

self.workerThread = [[NSThread alloc] initWithTarget:self selector:@selector(startRunLoop) object:nil];
[self.workerThread start];

哪个启动了runloop:

- (void)startRunLoop
{
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
    do {
        @autoreleasepool
        {
            [runLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];
        }
    } while (![NSThread currentThread].isCancelled);
}

现在,要在工作线程上启动计时器,您需要:

- (void)startTimer
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(timerEvent:) userInfo:nil repeats:YES];
}

如何致电:

[self performSelector:@selector(startTimer) onThread:self.workerThread withObject:nil waitUntilDone:NO];

希望它有所帮助。