我可以使用 NSTimer 或定期唤醒线程来定期调用函数。这两种方法的行为基本相同:
timer = [ NSTimer
scheduledTimerWithTimeInterval:1
target:self
selector:@selector(doSomething)
userInfo:nil
repeats:NO
];
和
@autoreleasepool {
BOOL continueProcessingQueue = YES;
while (continueProcessingQueue) {
[self performSelectorOnMainThread:@selector(doSomething) withObject:nil waitUntilDone:NO];
NSDate *curtainTime = [[NSDate alloc] initWithTimeIntervalSinceNow:10];
NSDate *currentTime = [[NSDate alloc] init];
while (continueProcessingQueue && ([currentTime compare:curtainTime] != NSOrderedDescending)) {
if ([self.processThread isCancelled] == YES) {
continueProcessingQueue = NO;
}
[NSThread sleepForTimeInterval:1];
currentTime = [[NSDate alloc] init];
}
}
}
使用计时器似乎要简单得多。是否存在第二种方法比使用计时器更可取的情况?