最简单的方法是将任务分成小块,并在计时器上执行它们,以便runloop可以处理UI事件:
static NSMutableArray *tasks;
- (void)addTask:(id)task
{
if (tasks == nil)
tasks = [[NSMutableArray alloc] init];
[tasks addObject:task];
if ([tasks count] == 1)
[self performSelector:@selector(executeTaskAndScheduleNextTask) withObject:nil afterDelay:0.0];
}
- (void)executeTaskAndScheduleNextTask
{
id task = [tasks objectAtIndex:0];
[tasks removeObjectAtIndex:0];
// Do something with task
NSLog(@"finished processing task: %@", task);
// Sechedule processing the next task on the runloop
if ([tasks count] != 0)
[self performSelector:@selector(executeTaskAndScheduleNextTask) withObject:nil afterDelay:0.0];
}
不过,后台线程有助于获得更好的用户体验,而且实际上可能更简单,这取决于您正在执行的操作。