在调用Web服务时使用performSelector for activityIndi​​cator的问题 - IOS

时间:2012-02-02 00:58:18

标签: ios xcode web-services uiactivityindicatorview performselector

我正在尝试让performSelector在进行Web服务调用时在单独的线程上加载活动指示器。问题是“return parsedData;”没有在fetchJSON中设置:但是,当我在getData:方法中打印parsedData时,它会恢复正常。我假设在performSelector完成数据之前正在执行返回。有没有办法让fetchJSON:方法在返回parsedData之前等待performSelector完成?

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

1 个答案:

答案 0 :(得分:0)

“performSelector在单独的线程上加载活动指示符”

...

UIKit通常不是线程安全的。

在注释掉的代码和令人困惑的方法声明之间(为什么getData:一个IBAction?它是从代码中调用还是作为控件的动作?),我真的错过了你想要在这里做什么的上下文。

您是否可以首先简要介绍一下您要完成的工作以及此代码如何适应该图片?