2

我正在尝试将数据从服务器存储到 NSMutable 数组,以将它们显示为表格视图中的新闻提要,如图所示。基本上就像推特新闻提要。我想做的是从 NSMutable 数组中的服务器获取数据,并使用该数组在我的表格视图中显示。我不知道这是否是正确的方法。我尝试静态添加并且它有效,但我真的不知道如何动态添加,因为我是 Objective C 的新手。对不起,如果这个问题看起来真的很愚蠢。提前致谢!

4

1 回答 1

2

使用 JSON 解析数据:

dispatch_queue_t jsonParsingQueue = dispatch_queue_create("jsonParsingQueue", NULL);

// execute a task on that queue asynchronously
dispatch_async(jsonParsingQueue, ^{
    NSString *urlStr = @"YourURL";
    NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
    [request setHTTPMethod: @"GET"];
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *responseStr = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    NSData * jsonData = [responseStr dataUsingEncoding:NSUTF8StringEncoding];

    NSMutableArray *tempResults = [NSMutableArray alloc];
    NSError *jsonParsingError = nil;
    NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&jsonParsingError];
    tempResults = jsonObject[@"posts"]; //Add the json key you would like to get

    self.arrayToDisplay = [tempResults copy]; //copy them to your NSMutableArray


    // some code on a main thread (delegates, notifications, UI updates...)
    dispatch_async(dispatch_get_main_queue(), ^{

        [self.myTableView reloadData];


    });
});
于 2013-11-13T15:29:01.343 回答