views:

37

answers:

1

I'm trying to set up a view that gives feed back via progress bar while it carries out a task, by incrementally sending updates to the view.

I don't know much about multithreading, so I'm trying to do this without using it. Is there a way to force a view to update? It seems like there should be something to do this, cause I'm not really waiting for input, just giving output, and things happen one at a time - carry out computation steps, update progress bar, carry out more steps, update bar, etc.

Thanks for any help with this.

+2  A: 

Easiest way is to divide the task into small chunks and perform them on a timer so the runloop can process UI events:

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];
}

A background thread makes for a much better user experience though, and may actually be simpler depending on what operation you are performing.

rpetrich
Brilliant, +1 for including the code.As for the UI, I really needed the task to finish before giving the user control, otherwise they will just have control while they wait for the thing they wanted in the first place in this case.
Alex Gosselin