我目前有一個非常簡單的視圖,它顯示來自JSON提要的信息。我遇到的問題是我按下此選項卡後遇到的第二次暫停。我如何使這個視圖立即加載,然後加載label.text區域?活動指標最好?JSON顯示文本 - 凍結UI
我應該使用線程嗎?
在此先感謝!
代碼:
- (NSString *)stringWithUrl:(NSURL *)url {
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:30];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
- (id)objectWithUrl:(NSURL *)url {
SBJsonParser *jsonParser = [SBJsonParser new];
NSString *jsonString = [self stringWithUrl:url];
return [jsonParser objectWithString:jsonString error:NULL];
}
- (NSDictionary *)downloadStats {
id response = [self objectWithUrl:[NSURL URLWithString:@"http://www.example.com/JSON"]];
NSDictionary *feed = (NSDictionary *)response;
return feed;
[feed release];
}
- (void)viewDidLoad {
[super viewDidLoad];
[GlobalStatsScrollView setScrollEnabled:YES];
[GlobalStatsScrollView setContentSize:CGSizeMake(320, 360)];
}
- (void)viewWillAppear:(BOOL)animated {
NSLog(@"View appears");
// Download JSON Feed
NSDictionary *feed = [self downloadStats];
totalproduced.text = [feed valueForKey:@"Produced"];
totalno.text = [feed valueForKey:@"Total"];
mostcommon.text = [feed valueForKey:@"Most Common"];
}
你可能想看看[JSONKit](https://github.com/johnezang/JSONKit)。它往往比其他JSON庫快得多,如果解析JSON代表了等待時間的相當一部分時間,可能會減少「凍結」時間。 – johne 2011-02-13 08:24:29