ios - 如何从JSON更新TableView

标签 ios json nsmutablearray tableview

我从JSON更新网络数据时遇到大问题。所以我有从JSON URL解析的简单TableView。当我按下按钮时-JSON信息写入tableviewCell,但我需要此信息随时更新。所以我有我的代码:

-(void)viewDidAppear:(BOOL)animated {

        [super viewDidAppear:animated];

        NSURL *url = [NSURL URLWithString:@"http://url.json"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];

        connection = [NSURLConnection connectionWithRequest:request delegate:self];
        if (connection) {
            webdata = [[NSMutableData alloc]init];

            [mytableview reloadData];

        }

我写了这段代码,但是我的信息没有更新,我在做什么错?我也尝试过ViewDidAppear,viewWillAppear。但是什么都没有。

添加了cellForRow方法。
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{



    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(! cell)
    {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]autorelease];
    }



    cell.textLabel.text = [array objectAtIndex:indexPath.row];

最佳答案

尝试使用基于块的NSURLConnection。我想您形成网络数据的方式就是问题所在。

NSURL *url = [NSURL URLWithString:@"http://url.json"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:urlRequest
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *urlResponse, NSData * webdata, NSError *reponseError) {

    NSArray *json = [NSJSONSerialization JSONObjectWithData: webdata
                                                    options:0
                                                      error:nil];
    for (NSDictionary *person in json) {
        //Are these numbers or strings
        NSString *art = person[@"artist"];
        NSString *song2 = person[@"start"];
        [array addObject:art];
        [array2 addObject:song2];
    }
    [mytableview reloadData];

}];

不建议保留两个数组以仅显示歌手姓名和歌曲名称。数据格式正确。这样将这些数据保存在数组中。在tableView:cellForRowAtIndexPath:中,当您需要使用索引显示数据时,请提取人员并找到相应的名称和歌曲名称。

关于ios - 如何从JSON更新TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17341502/

相关文章:

ios - 如何优化过滤器性能 CIFilter

java - HTTP GET 响应解析错误(空字符串?) - 但正文不为空

json - 从 post 方法中检索 json 数据并附加到数组

ios - 不明白如何在动态填充列表时正确使用数组

iphone - NSUrlConnection 委托(delegate) - 获取 http 状态代码

ios - 无法在 swift 的子文件夹中找到图像?

iOS:存储联系信息和 GPS 坐标的最佳方式

ios - Swift:将字符串转换为 NSMutableArray

键盘显示后的iOS分屏宽度

java - Android JsonObject 错误 org.json.JSONException : No value