NSTimer with anonymous function / block?

牧云@^-^@ 提交于 2019-11-30 01:14:38

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.

https://github.com/mBrissman/NSTimer-Block

As of late 2018, you do it precisely like this:

Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { timer in
  print("no, seriously, this works on iPhone")
} 

This thanks to @JohnnyC !

Truly strange!

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!