Is it possible to update views while doing a task without multithreading in iPhone OS?
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 thi开发者_如何学Gos.
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.
精彩评论