NSTimer with anonymous function / block?

前端 未结 9 2337
囚心锁ツ
囚心锁ツ 2020-12-25 10:17

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

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-25 10:55

    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.

提交回复
热议问题