2010-06-16 20 views
6

方法調用我嘗試做多線程的目的C. 我想現在要做的是, 爲對象的一些實例, 我希望有辦法調用一些功能5秒鐘後。 我該怎麼做?如何計劃的目標C

在Coco 2D中,這很容易做到。他們有一些叫做調度器的東西。在目標C中,請問該怎麼做?

感謝

回答

13

您可以使用performSelector:withObject:afterDelay

例如:

[self performSelector:@selector(myFunc:) withObject:nil afterDelay:5.0]; 
+0

感謝。還感興趣的: +(無效)cancelPreviousPerformRequestsWithTarget:(ID)aTarget選擇:(SEL)aSelector對象:(ID)anArgument – 2012-12-05 05:26:18

+0

上面的代碼有一個錯誤,則:後不需要用於不帶參數的方法的選擇呼叫。 [self performSelector:@selector(myFunc)withObject:nil afterDelay:5.0]; – archieoi 2013-09-06 12:52:27

2

添加到說了些什麼,如果你想一個參數傳遞給myFunc的,該呼叫可以修改如下:

[self performSelector:@selector(showNote:) withObject:@"S" afterDelay:1.0]; 

,如果你需要調用一個需要超過1個參數的方法,你可以做,用調用如下面的代碼片段 -

SEL selector = @selector(nextPicture:); 
NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:selector]; 
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; 
[invocation setSelector:selector]; 

//Set the arguments 
[invocation setTarget:self]; 
NSString* str = [imageNames objectAtIndex:1]; 
[invocation setArgument:&str atIndex:2]; 
[NSTimer scheduledTimerWithTimeInterval:5.0f invocation:invocation repeats:NO]; 
+1

在轉向'NSInvocation'之前,我會推薦使用'dispatch_after'。只需在Xcode中輸入並接受自動完成,並將代碼在塊中延遲後執行。 – MaxGabriel 2013-05-07 07:06:54

+0

不錯的推薦,謝謝! – 2013-05-07 08:42:02

+0

dispatch_after是一個很好的建議,實際上我到現在還不知道。這是一個非常有用的代碼片段,因爲它使得它更容易調用有一個或多個參數容易得多(行或多個方法)的方法。基本上,延遲塊調用比限制單個選擇器更有用。 – Corbin87 2013-12-29 18:27:45