ios - 如何从服务器将数据存储在 NSmutable 数组中

标签 ios nsmutablearray

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

最佳答案

使用 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];


    });
});

关于ios - 如何从服务器将数据存储在 NSmutable 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19957380/

相关文章:

ios - unwind segue 在文本框值等于 nil 时取消

ios - Storyboard中带有不同颜色文本的 UILabel

ios - 挑战 : Best way to check if model object array contains properties of model in Objective-C

ios - 从 NSMutableArray 中获取数据

objective-c - 释放 NSMutableArray 不影响数组中元素的数量

iphone - NSMutableArray 抛出 NSInvalidArgumentException-Object 不能为 nil

ios - audioPlayerDidFinishPlaying 用法

ios - 无法使用 Github 操作构建 iOS 项目

ios - AVPlayer:当视频和设备的宽高比不同时,为什么 iPhone 视频不会失真?

objective-c - NSMutableArray 排序任务