2016-04-27 57 views
-1

我創建NSTimer我可以在另一個NStimer中使用NStimer嗎?

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

在該方法sendImage,我創建另一個NSTimertimer2。代碼如下:

- (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()中的每個循環都可以間隔運行。

+5

「但它沒有工作」 - 它產生了一個錯誤,炸燬,炒雞蛋;-)等?細節將幫助人們幫助你。編輯您的問題以添加詳細信息,並且有人可能會提供幫助。 – CRD

+0

第一個計時器是否正常工作?調用sendImage方法嗎? –

+1

您正在重新創建計時器50次?這應該如何工作? – trojanfoe

回答

0

您的問題的答案是YES。可以在另一個觸發回調中安排一個定時器。試想一下:

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"); 
} 

即使問題沒有充分的說明,我會盡力猜測,根本原因是中計時器多麼第一次計劃。

你需要線程與aproprietaly設置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]; 

希望它能幫助。

+0

非常感謝,我的朋友......但它不適合我的程序。 –

+0

@X。羅迪,可能我誤解了你的問題。它看起來像你有興趣在「異步像圖片發送」而不是「在另一個計時器內調度計時器內回調」。 –

+0

您的回答在另一個問題上的確幫助我。再次感謝。 –