2011-02-10 40 views
0

我目前有一個非常簡單的視圖,它顯示來自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"]; 
    } 
+0

你可能想看看[JSONKit](https://github.com/johnezang/JSONKit)。它往往比其他JSON庫快得多,如果解析JSON代表了等待時間的相當一部分時間,可能會減少「凍結」時間。 – johne 2011-02-13 08:24:29

回答

1
- (void)viewWillAppear:(BOOL)animated { 
    NSLog(@"View appears"); 

    UIActivityIndicatorView* spiner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhiteLarge]; 
    spiner.tag = 123; 
    [self.view addSubview: spiner]; 
    [spiner startAnimating]; 
    [spiner release]; 

    NSThread* thread = [[NSThread alloc] initWithTarget: self 
               selector: @selector(loadFeed) object: nil]; 
    [thread start]; 

} 

-(void) loadFeed { 
    // Download JSON Feed 
    NSDictionary *feed = [self downloadStats];  
    totalproduced.text = [feed valueForKey:@"Produced"]; 
    totalno.text = [feed valueForKey:@"Total"]; 
    mostcommon.text = [feed valueForKey:@"Most Common"]; 

    [[self.view viewWithTag: 123] removeFromSuperview]; 
} 

別忘後釋放你的線程。 你也應該檢查NSOperationQueue的文檔

另一種選擇是使用異步請求。

+0

完美!這工作完美。你有沒有機會知道如何使用活動指標而不是默認的標籤文字? – 2011-02-10 07:15:30

1

問題是,-[NSURLConnection sendSynchronousRequest:]阻塞,直到它具有所有的數據。

解決此問題的最佳方法是實現異步請求(請參閱NSURLConnection參考資料,瞭解如何執行此操作)。

你也可以在Max建議的後臺線程中進行同步連接,但我建議使用performSelectorInBackground:而不是手動創建線程。無論哪種方式,不要忘記在新線程中先設置一個NSAutoreleasePool以避免泄漏,並且請注意調用GUI方法(如設置UILabel的文本)需要在主線程上完成,例如使用performSelectorOnMainThread:withObject:waitUntilDone: 。正如你所看到的,線程版本存在一些缺陷,所以我真的建議實現一個異步連接。