Trying to show an UIActivityIndicatorView but it doesn't start until the function...

Discussion in 'iOS Programming' started by detz, Oct 2, 2010.

  1. detz macrumors 65816

    Joined:
    Jun 29, 2007
    #1
    So at the beginning of my function I create a UIActivityIndicatorView and add to the subview. I start it and then I perform another long running function but what happens is the function runs and the UIActivityIndicatorView shows up only after it's done. It's like it's being added to a queue and not running in time before the operation starts. Is there an easy way to tell it to go and then continue?
     
  2. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    The UI only updates on the main thread and only on each time round the run loop. So if you are doing something long running on the main thread (which you are) then you are blocking any update to the UI including the adding of your progress indicator. You need to do your long running operation in the background.
     
  3. jtrue macrumors newbie

    jtrue

    Joined:
    Mar 7, 2010
    Location:
    Beech Mountain, NC
    #3
    or wherever you call your long running function set the UIActivityIndicatorView before and after the call.
     
  4. idelovski macrumors regular

    Joined:
    Sep 11, 2008
    #4
    Activity indicator needs one pass through the run loop at least once before it starts its twirl. Make an instance variable and split everything in two methods.

    Code:
    - (void)startTheJob
    {
       UIActivityIndicatorView  *tmpActIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    
       self.actIndicatorView = tmpActIndicator;
       
       [tmpActIndicator release];
       
       self.actIndicatorView.hidden = NO;
       self.actIndicatorView.center = self.view.center;
       
       [self.view addSubview:self.actIndicatorView];
       [self.actIndicatorView startAnimating];
    
       [self performSelector:@selector(doTheJob) withObject:nil afterDelay:.1];
    }
    
    - (void)doTheJob
    {
       // Perform lenghty operation here
    
       [self.actIndicatorView stopAnimating];
       [self.actIndicatorView removeFromSuperview];
       self.actIndicatorView = nil;
    }
    
    This will do the trick if you have no other option. But otherwise, NSOperation is so cute and simple to master, you should learn how to use it.
     

Share This Page