假设您有一些类属性:
@interface ViewController ()
@property (nonatomic, strong) NSArray *array;
@end
只需使用NSJSONSerialization
:
NSError *error;
NSData *data = [NSData dataWithContentsOfURL:url];
self.array = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
如果您想将数组保存在您的Documents
文件夹中以进行持久存储,以便在将来调用应用程序时进行检索,您可以:
NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filename = [docsPath stringByAppendingPathComponent:@"results.plist"];
[self.array writeToFile:filename atomically:NO];
稍后在下次调用时从文件中读取它(以防您不想从服务器重新检索它):
NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filename = [docsPath stringByAppendingPathComponent:@"results.plist"];
self.array = [NSData dataWithContentsOfFile:filename];
要将它用于 a UITableView
,您可以将其存储在类属性中并响应适当的UITableViewDataSource
方法:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
NSDictionary *rowData = self.array[indexPath.row];
NSDictionary *fields = rowData[@"fields"];
cell.textLabel.text = fields[@"message"];
cell.detailTextLabel.text = fields[@"message_detail"];
return cell;
}