iPhone UITableView从connectionDidFinishLoading填充

时间:2010-02-06 21:15:19

标签: iphone objective-c json uitableview nsurlconnection

我一直在努力想要解决这个问题。我有一些来自NSURLConnection的JSON。这工作正常,我已将其解析为数组。但我似乎无法从connectionDidFinishLoading方法中获取数组。我在UITableViewCell方法中得到(null)。我假设这是一个保留问题的范围,但我对ObjC这么新,我不知道该怎么办。任何帮助将不胜感激。
欢呼声。

-(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;

}

4 个答案:

答案 0 :(得分:2)

解决方案:
在使用self.tableArray获取kubi和st3fan的建议后,我发现我必须使用[self.tableView reloadData];重新加载tableView

答案 1 :(得分:0)

  1. 摆脱第二行的[connection release]connection对象是自动释放的,因此可能会导致崩溃。
  2. 看起来你有一个名为tableArray的房产?如果是这样,您将在此方法中重新声明名称(您应该已经获得编译器警告)。
  3. 第二个想法,这是方法的第二个1/2看起来如何:

    NSMutableArray *tmpArray = [[NSMutableArray alloc] initWithObjects:nil];
    
    for (NSString *element in dataArray) {
        [tmpArray addObject:[element objectForKey:@"name"]];
    }
    
    self.tableArray = tmpArray;
    [tmpArray release];
    

答案 2 :(得分:0)

connectionDidFinishLoading:中,您使用声明tableArray作为局部变量。因此,永远不会将其分配给self.tableArray

答案 3 :(得分:0)

我遇到了同样的问题,我决定重新加载表格。

我在connectionDidFinishLoading函数

的末尾插入了这一行
[self.tableView reloadData];    

它有效。