Question

I'm trying to get the performSelector to load the activity indicator on a separate thread while the web service call is made. The issue is the "return parsedData;" is not being set in fetchJSON:. However, when I print the parsedData in getData: method, it's coming back fine. I assume the return is being executed before the performSelector is finished getting the data. Is there any way to have the fetchJSON: method wait for performSelector to finish before returning parsedData?

-(void)showActivityIndicator
{ 
    CGRect frame = CGRectMake(0.0, 0.0, 125.0, 125.0);
    loading = [[UIActivityIndicatorView alloc] initWithFrame:frame];
    [loading setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [loading hidesWhenStopped];
    //loading.center=[self tableView].center;
    [loading startAnimating];
    [loading sizeToFit];
    loading.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin |
                                UIViewAutoresizingFlexibleRightMargin |
                                UIViewAutoresizingFlexibleTopMargin |
                                UIViewAutoresizingFlexibleBottomMargin);

    // initing the bar button
    //UIBarButtonItem *loadingView = [[UIBarButtonItem alloc] initWithCustomView:loading];
    //loadingView.target = self;

    [loadingView addSubview:loading];
}


- (NSDictionary *)fetchJSON:(NSString *)urlString
{
    NSMutableString *domain = [[NSMutableString alloc] initWithString:@"http://www.blablabla.com/dev/"];
    [domain appendString:urlString];
    //NSLog(@"%@", domain);
    NSURL *url = [NSURL URLWithString:domain];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];

    [self showActivityIndicator];
    [self performSelector:@selector(getData:) withObject:req afterDelay:0.0];
    //[self performSelectorOnMainThread:@selector(getData:) withObject:req waitUntilDone:YES];

    return parsedData;
}

-(IBAction)getData:(id)sender
{   
    NSURLResponse* response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:sender returningResponse:&response error:nil];
    parsedData = [NSJSONSerialization
                  JSONObjectWithData:data
                  options:NSJSONReadingMutableLeaves
                  error:nil];
    NSLog(@"GET DATA %@", parsedData);
    [loading stopAnimating];
    loading = nil;
}
Was it helpful?

Solution

"performSelector to load the activity indicator on a separate thread"

??

UIKit is, in general, not thread safe.

Between the commented out code and confusing method declarations (why is getData: an IBAction? Is it called both from within code and as a control's action?), I'm really missing context on what you are trying to do here.

Could you start by just giving a high-level overview of what you're trying to accomplish and how this code fits into that picture?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top