2010-07-15 97 views
3

我需要为我的iPhone objective-c应用程序添加一个暂停/等待功能。 sleep()函数对我不起作用。需要objective-c暂停/等待功能

需要在这两者之间添加暂停/等待功能。

myscore += [self getcard]; 

myscore += [self getcard]; 
+0

'sleep()'不起作用,因为它会阻止它从中被调用。这是你阻止所有事件的UI /主线程。 – 2010-07-15 22:02:07

回答

3

我还没有看到的Objective-C这样的功能,但我已经使用一个NSTimer这就要求在你决定一个时间间隔给定函数。

http://developer.apple.com/iphone/library/documentation/cocoa/reference/foundation/Classes/NSTimer_Class/Reference/NSTimer.html

更具体地使用功能scheduledTimerWithTimeInterval:目标:选择器:USERINFO:重复:确实对我来说。时间间隔以秒为单位,每个tick之间的“睡眠”时间,target是持有应该调用的函数的类,选择函数。

scheduledTimerWithTimeInterval:1   // Ticks once per second 
         target:myObject // Contains the function you want to call 
         selector:@selector(myFunction:) 
         userInfo:nil 
         repeats:YES 
1

如果您将等待的代码分开,您可以使用performSelector:withObject:afterDelay:在延迟后调用该选择器。

实施例,退出该应用程序在5秒后:

[NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:5.0]; 
3

这将运行[NSRunLoop currentRunLoop] 2秒,同时暂停当前的方法,使你能够处理输入和其他的东西同时:

[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]]; 
0

您可以使用GCD(grand central dispatch)的dispatch_after方法,如

myscore += [self getcard]; 

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ 
    myscore += [self get card]; 
});