代码之家  ›  专栏  ›  技术社区  ›  Alex Gosselin

在iPhone操作系统中,在执行任务时是否可以不使用多线程来更新视图?

  •  0
  • Alex Gosselin  · 技术社区  · 15 年前

    我正在尝试设置一个视图,它在执行任务时通过进度条提供反馈,方法是以增量方式向视图发送更新。

    谢谢你的帮助。

    1 回复  |  直到 15 年前
        1
  •  2
  •   rpetrich    15 年前

    最简单的方法是将任务分成小块,并在计时器上执行它们,以便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];
    }
    

    不过,后台线程有助于获得更好的用户体验,而且实际上可能更简单,这取决于您正在执行的操作。