2

I'm using a UISearchBar in my application and the problem is when I call a few json methods searchBarSearchButtonClicked seems to not resign the keyboard until the other methods are done loading the data. I've tried alternatively using UIAlertView and UIButtons to replace the searchBarSearchButtonClicked function but they appear to literally freeze and stay in a "pressed down" state too. I was also wondering if this would be a reason why [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; wouldn't show an activity indicator in the device's status bar.

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    self.args = searchBar.text;
    [self grabData];
    [self fillVars];
    [searchBar resignFirstResponder];
    [self.tableView reloadData];
}

[self grabData] is where I grab the JSON data and [self fillVars] just fills a few things that are later used.

-(void)grabData{
    self.args = [self.args stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

urlString = [NSString stringWithFormat:@"%@%@?key=%@&q=%@",baseUrl,func,apiKey,args];
url = [NSURL URLWithString:urlString];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSError *error; 
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
self.matches = [json objectForKey:@"matches"];
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;

}
4

1 回答 1

1

您将不得不使用线程。对界面的所有操作都发生在主线程上,因此当您在主线程上执行冗长的任务时,界面将无法在任务完成之前自行更新。

在 UIViewController 中,您可以执行 [self performSelectorInBackground:@selector(grabData) withObject:self],这是一种使用大中央调度调度新队列(线程)的便捷方法。

您也可以使用 GCD API 手动执行此操作。您会按照以下方式做一些事情:

dispatch_queue_t jsonQueue = dispatch_queue_create("JSON Queue", NULL);
dispatch_async(jsonQueue, ^{

    // fetch JSON data ...

    dispatch_async(dispatch_get_main_queue(), ^{

        // perhaps do something back on the main queue once you're done!

    });
});
于 2012-05-09T00:44:40.107 回答