簡體   English   中英

最好的方法是將此JSON數據保留在iOS 6中的UITableView中使用

[英]Best way persist this JSON data for use in a UITableView in iOS 6

我的服務器正在向我發送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並保留下次啟動的數據。

假設你有一些類屬性:

@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];

要將它用於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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM