2010-02-06 69 views
1

我一直在嘗試幾個小時來弄清楚這一點。我有一個來自NSURLConnection的JSON。這工作正常,我已經解析成一個數組。但我似乎無法從connectionDidFinishLoading方法中獲取數組。我在UITableViewCell方法中獲取(null)。我認爲這是一個保留問題的範圍,但我對於ObjC來說是如此的新鮮,我不知道該怎麼做。任何幫助將不勝感激。
乾杯。從連接添加iPhone UITableViewDDFinishLoading

-(void)connectionDidFinishLoading:(NSURLConnection *)connection { 
[connection release]; 

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
[responseData release]; 

SBJSON *json = [[SBJSON alloc] init]; 

NSDictionary *results = [json objectWithString:responseString]; 

self.dataArray = [results objectForKey:@"data"]; 

NSMutableArray *tableArray = [[NSMutableArray alloc] initWithObjects:nil]; 

for (NSString *element in dataArray) { 
    //NSLog(@"%@", [element objectForKey:@"name"]); 
    NSString *tmpString = [[NSString alloc] initWithString:[element objectForKey:@"name"]]; 
    [tableArray addObject:tmpString]; 
} 
} 

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

static NSString *CellIdentifier = @"Cell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
} 

// Configure the cell. 
//cell.textLabel.text = [self.tableView objectAtIndex:indexPath.row]; 

cell.textLabel.text = [self.tableArray objectAtIndex:indexPath.row]; 
NSLog(@"%@", tableArray); 
return cell; 

} 

回答

0
  1. 得到二號線擺脫[connection release]的。 connection對象進入autoreleased,所以這可能會導致崩潰。
  2. 它看起來像你有一個名爲tableArray?如果是這樣,你在這個方法中重新聲明名稱(你應該得到一個編譯器警告)。

關於第二個想法,這裏是如何的方法的第二個1/2應該是:

NSMutableArray *tmpArray = [[NSMutableArray alloc] initWithObjects:nil]; 

for (NSString *element in dataArray) { 
    [tmpArray addObject:[element objectForKey:@"name"]]; 
} 

self.tableArray = tmpArray; 
[tmpArray release]; 
+0

kubi。 我試過這種方式,我仍然在UITableVIewCell方法中爲null?但是我在connectionDidFinishLoading中獲得了正確的值。它仍然陷在那裏... 感謝您的幫助。 –

+0

我注意到: 2010-02-06 13:38:07.907課程[34368:207](null) 2010-02-06 13:38:07.908課程[34368:207](null) 2010-02 -06 13:38:07.910課程[34368:207](null) 2010-02-06 13:38:07.952課程[34368:207]( 「我的高爾夫球場」, 「Glen Annie」, 「Alisal牧場「, 」聖巴巴拉高爾夫俱樂部「, 」蘭喬聖馬科斯「 ) UITableViewCell似乎在connectionDidFinishLoading之前加載。所以價值觀還不存在...... –

0

connectionDidFinishLoading:使用聲明tableArray作爲一個局部變量。因此它永遠不會被分配到self.tableArray

2

解決方案:
以庫比什和st3fan的建議與self.tableArray後,我發現我不得不重新加載的tableView與[self.tableView reloadData];

+0

很高興爲您做了一切! PS。你應該標記我們的答案是正確的。 – kubi

0

我有同樣的問題,我解決它重裝表。

我插入這條線在connectionDidFinishLoading功能

[self.tableView reloadData];  

的結束和它的作品。