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 block
A block based timer API exists in Cocoa (as of iOS 10+ / macOS 10.12+) – here's how you can use it from Swift 3 onwards:
Timer(timeInterval: gameInterval, repeats: false) { _ in
print("herp derp")
}
… or in Objective-C:
[NSTimer scheduledTimerWithTimeInterval:gameInterval repeats:NO block:^(NSTimer *timer) {
NSLog(@"herp derp");
}];
As noted in a comment, be careful not to use strong self references inside the block to avoid retain cycles (for more info).
If you need to target OS versions older than iOS10, macOS 12, tvOS 10, watchOS 3, you should use one of the other solutions.