开发者

Need objective-c Pause/Wait function

I need to add a Pause/Wait function to my iPh开发者_开发百科one objective-c app. The function sleep() doesn't work for me.

Need to Add Pause/Wait Function between both of these.

myscore += [self getcard];

myscore += [self getcard];


I haven't seen such a function for objective-c, but I have used an NSTimer which calls a given function in a time-interval that you decide.

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

More specifically using the function scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: does it for me. Time interval is in seconds the "sleep" time between each tick, target is the class holding the function that should be called, selector the function.

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


This will run [NSRunLoop currentRunLoop] for 2 seconds while pausing the current method, enabling you to handle input and other stuff meanwhile:

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


If you separate the code for what happens after the wait, you can use performSelector:withObject:afterDelay: to call that selector after a delay.

Example, quit the application after 5 seconds:

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


You can use the dispatch_after method from GCD (grand central dispatch) like so

myscore += [self getcard];

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜