tags:

views:

166

answers:

2

I'm trying to do something like this:

- (void)sectionChanged:(id)sender {
    [self.view addSubview:loadingView];
    // Something slow
    [loadingView removeFromSuperview];
}

where loadingView is a semi-transparent view with a UIActivityIndicatorView. However, it seems like added subview changes don't take effect until the end of this method, so the view is removed before it becomes visible. If I remove the removeFromSuperview statement, the view shows up properly after the slow processing is done and is never removed. Is there any way to get around this?

+4  A: 

Run your slow process in a background thread:

- (void)startBackgroundTask {

    [self.view addSubview:loadingView];
    [NSThread detachNewThreadSelector:@selector(backgroundTask) toTarget:self withObject:nil];

}

- (void)backgroundTask {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    // do the background task

    [self performSelectorOnMainThread:@selector(backgroundTaskDone) withObject:nil waitUntilDone:NO];
    [pool release];

}

- (void)backgroundTaskDone {

    [loadingView removeFromSuperview];
}
Tom Irving
Excellent, thanks. dannywartnaby's answer is nearly identical but I'm making yours accepted for remembering an autorelease pool.
Rob Lourens
+1  A: 
dannywartnaby