0

我的服务器正在向我发送 JSON 响应,如下所示:

[
  {
    "fields": {
      "message": "Major Network Problems", 
      "message_detail": "This is a test message"
    }, 
    "model": "notification", 
    "pk": 5
  }, 
  {
    "fields": {
      "message": "test", 
      "message_detail": "Some content"
    }, 
    "model": "notification", 
    "pk": 4
  }, 
  {
    "fields": {
      "message": "Test Message", 
      "message_detail": "Testing testing"
    }, 
    "model": "notification", 
    "pk": 3
  }
]

我想用每个项目的一行填充一个 UITableView,只显示字段的值,message然后我将点击该行以显示一个包含messagemessage_detail值的新视图。这些消息可能会在以后pk维护该值的日期更新,因此保留该信息可能很重要。

解析这些数据并将其持久化以供下次启动应用程序使用的最合适和最有效的方法是什么?

我认为 plist 将是一个好方法,但我希望看到一些建议,包括一些关于如何最好地从提供的 JSON 数组到填充 UITableView 并为下次启动保留数据的代码。

4

1 回答 1

2

假设您有一些类属性:

@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;
}
于 2013-02-05T13:36:28.057 回答