我正在尝试将数据从服务器存储到NSMutable数组,以在表格视图中将它们显示为新闻源,如此image所示。基本上像推特新闻源。我想做的是从NSMutable数组中的服务器获取数据,并使用该数组在我的表视图中显示。我不知道这是否是正确的方法。我尝试静态添加它可以工作,但我真的不知道如何动态,因为我是Objective C的新手。抱歉,如果这个问题看起来真的很愚蠢。提前谢谢!
答案 0 :(得分: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];
});
});