2013-07-31 23 views
2

我在正在工作的表視圖中加載4個城市字符串,但是當我選擇其中一個單元格並導航到其他表格時,導航速度太慢。我在下面的另一個表中使用了不同鏈接的代碼。你能告訴我爲什麼需要很長時間(〜4 - 6秒)才能看到另一種觀點嗎?在JIT中慢速瀏覽UITableView問題

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 

NSURL * url = [NSURL URLWithString:@"http://kalkatawi.com/jsonTest.php"]; 

NSData * data = [NSData dataWithContentsOfURL:url]; 

NSError *e = nil; 

jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e]; 

jsonArray1 = [[NSMutableArray alloc] init]; 

for(int i=0;i<[jsonArray count];i++) 
{     
    NSString * city = [[jsonArray objectAtIndex:i] objectForKey:@"city"]; 

    [jsonArray1 addObject:city]; 
} 

-

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

NSString *tempString = [jsonArray1 objectAtIndex:indexPath.row]; 
cell.textLabel.text = tempString; 
return cell; 
} 

-

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

SeconfViewController *second = [[SeconfViewController alloc] initWithNibName:@"SeconfViewController" bundle:nil]; 

UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath]; 

NSString *cellText = selectedCell.textLabel.text; 

NSString *edit = [NSString stringWithFormat:@"http://kalkatawi.com/jsonTest.php?d=1&il=%@", cellText]; 

second.str2 = edit; 

[self.navigationController pushViewController:second animated:YES]; 

} 
+0

聽起來像你正在做的是在主線程上進行同步網絡調用。尋找進行異步網絡調用的方法。有很多例子。 –

回答

0

也許是因爲你是下載同步,你是阻塞主線程,也許就是這個原因,你的應用程序凍結4-6秒,試着下載你的異步json

- (void)viewDidLoad 
{ 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    NSData *response = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://kalkatawi.com/jsonTest.php"]]; 
    NSError *parseError = nil; 
    jsonArray = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&parseError]; 
    jsonArray1 = [[NSMutableArray alloc] init] 
     for(int i=0;i<[jsonArray count];i++) 
     {     
      NSString * city = [[jsonArray objectAtIndex:i] objectForKey:@"city"]; 

      [jsonArray1 addObject:city]; 
     } 
    } 
    dispatch_sync(dispatch_get_main_queue(), ^{ 
      [self.myTableView reloadData]; 
     }); 
}); 
} 
+0

NSData的'initWithContentsOfURL:'不應該用於訪問_remote_資源。該文檔對此一事無言,但在Apple官方開發人員論壇上,Apple的許多工程師聲明說'initWithContentsOfURL:'方法系列只能用於_file access_。使用'NSURLConnection'通過網絡訪問遠程資源。 – CouchDeveloper

+0

@CouchDeveloper @CarlosVela現在它運行得比以前更好。我已經提到過;首先它顯示'UITableView',然後加載數據是否有改善這個問題呢? –

+0

@LaiKalkatawi嘗試使用活動指示器來指示用戶數據正在從您的Web服務下載。 –

1

因爲您正在同步加載服務器中的數據,所以需要更多時間在其他屏幕上導航。在iOS中,所有用戶界面都在主線程上完成,並通過在主線程上進行數據調用來阻止它。我知道處理這個問題的最好方法是使用GCD(Grand Central Dispatch)。這是iOS中的一個API,它可以毫不費力地爲您產生線程。你只需要告訴你想要調用在後臺線程上從服務器加載數據。當你這樣做時,視圖應該瞬間導航。您可以在數據到來時使用活動指示器。

dispatch_async(dataQueue, ^{ 

     // Load all your data here 

     dispatch_async(dispatch_get_main_queue(), ^{ 
      // Update the UI 

     }); 

    });