有的時候 NSTimer
的調(diào)度任務(wù)比較復(fù)雜衅檀,需要在調(diào)度方法中執(zhí)行異步操作盗似,并且在異步操作中需要回調(diào)原方法中的回調(diào)參數(shù)。
Swift 3 介紹了一個帶有 block 回調(diào)的新方法:
Timer(timeInterval: gameInterval, repeats: false) { _ in
print("herp derp")
}
Objective-C 也有對應(yīng)的版本:
[NSTimer scheduledTimerWithTimeInterval:gameInterval repeats:NO block:^(NSTimer *timer) {
NSLog(@"herp derp");
}];
但這個方法需要 target 系統(tǒng)版本大于等于 iOS10, macOS 12, tvOS 10, watchOS 3。
如果項目需要支持以上系統(tǒng)以下的版本的時候锦针,需要怎么做呢?
我們可以用一種很聰明的方法來實現(xiàn):
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.7
target:[NSBlockOperation blockOperationWithBlock:^{ /* do this! */ }]
selector:@selector(main)
userInfo:nil
repeats:NO
];
完美置蜀!