I want to be able to schedule three small events in the future without having to write a function for each. How can I do this using NSTimer
? I understand blocks facilitate anonymous functions but can they be used within NSTimer
and if so, how?
[NSTimer scheduledTimerWithTimeInterval:gameInterval
target:self selector:@selector(/* I simply want to update a label here */)
userInfo:nil repeats:NO];
You can actually call:
NSTimer.scheduledTimerWithTimeInterval(ti: NSTimeInterval,
target: AnyObject,
selector: #Selector,
userInfo: AnyObject?,
repeats: Bool)
Use it like this:
NSTimer.scheduledTimerWithTimeInterval(1,
target: NSBlockOperation(block: {...}),
selector: #selector(NSOperation.main),
userInfo: nil,
repeats: true)
You can make use of dispatch_after if you want to achieve something similar to NSTimer and block execution.
Here is the sample code for the same:
int64_t delayInSeconds = gameInterval; // Your Game Interval as mentioned above by you
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
// Update your label here.
});
Hope this helps.
A block based timer API exists in Cocoa (as of iOS 10+ / macOS 10.12+) – here's how you can use it in Swift 3:
Timer(timeInterval: gameInterval, repeats: false) { _ in
print("herp derp")
}
… or in Objective-C:
[NSTimer scheduledTimerWithTimeInterval:gameInterval repeats:NO block:^(NSTimer *timer) {
NSLog(@"herp derp");
}];
If you need to target OS versions older than iOS10, macOS 12, tvOS 10, watchOS 3, you should use one of the other solutions.
Objective-C version of @Peter Peng's answer:
_actionDelayTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Well this is useless.");
}] selector:@selector(main) userInfo:nil repeats:YES];
It's pretty easy, but it isn't included in Apple framework, not yet at least.
You can write a block-based wrapper for NSTimer
yourself, e.g. using GCD, or you can use existing 3rd-party libraries like this one: https://github.com/jivadevoe/NSTimer-Blocks.
I have created a category on NSTimer witch makes it possible to use it with blocks.
I love this hack @Peter-Pang!! BlockOperation is created on the fly, own by the Timer which itself is own by the running queue, and call the main selector on the block to run it.... nice!!!
Updated for Swift 3
Timer.scheduledTimer(timeInterval: 1, target: BlockOperation {
// ...
}, selector: #selector(Operation.main), userInfo: nil, repeats: false)
来源:https://stackoverflow.com/questions/14924892/nstimer-with-anonymous-function-block