Chr*_*ris 42 iphone objective-c nstimer
我希望能够在将来安排三个小事件,而不必为每个事件编写一个函数.我怎么能用这个NSTimer呢?我理解块有助于匿名功能,但它们可以在内部使用NSTimer,如果是,如何使用?
[NSTimer scheduledTimerWithTimeInterval:gameInterval
target:self selector:@selector(/* I simply want to update a label here */)
userInfo:nil repeats:NO];
Run Code Online (Sandbox Code Playgroud)
Ren*_*nes 56
如果要实现类似于NSTimer和块执行的操作,可以使用dispatch_after.
以下是相同的示例代码:
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.
});
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
Pet*_*eng 26
你实际上可以打电话:
NSTimer.scheduledTimerWithTimeInterval(ti: NSTimeInterval,
target: AnyObject,
selector: #Selector,
userInfo: AnyObject?,
repeats: Bool)Run Code Online (Sandbox Code Playgroud)
像这样使用它:
NSTimer.scheduledTimerWithTimeInterval(1,
target: NSBlockOperation(block: {...}),
selector: #selector(NSOperation.main),
userInfo: nil,
repeats: true)Run Code Online (Sandbox Code Playgroud)
mz2*_*mz2 17
Cocoa中存在基于块的计时器API(从iOS 10+/macOS 10.12+开始) - 以下是如何在Swift 3中使用它:
Timer(timeInterval: gameInterval, repeats: false) { _ in
print("herp derp")
}
Run Code Online (Sandbox Code Playgroud)
......或在Objective-C中:
[NSTimer scheduledTimerWithTimeInterval:gameInterval repeats:NO block:^(NSTimer *timer) {
NSLog(@"herp derp");
}];
Run Code Online (Sandbox Code Playgroud)
如果您需要定位早于iOS10,macOS 12,tvOS 10,watchOS 3的操作系统版本,则应使用其他解决方案之一.
Objective-C版@Peter Peng的答案:
_actionDelayTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Well this is useless.");
}] selector:@selector(main) userInfo:nil repeats:YES];
Run Code Online (Sandbox Code Playgroud)
这很简单,但它不包含在Apple框架中,至少还没有.
您可以为NSTimer自己编写基于块的包装器,例如使用GCD,或者您可以使用现有的第三方库,如下所示:https://github.com/jivadevoe/NSTimer-Blocks.
| 归档时间: |
|
| 查看次数: |
20820 次 |
| 最近记录: |