【问题标题】:Storing json data on the iPhone: save the json string as it is VS make an object from json and use NSCoding + NSKeyedArchiver在 iPhone 上存储 json 数据:按原样保存 json 字符串 VS 从 json 创建一个对象并使用 NSCoding + NSKeyedArchiver
【发布时间】:2011-06-23 11:49:52
【问题描述】:

在我的 iPhone 应用程序中,我从远程服务器获取 json 数据,使用 Json 框架对其进行解析并将其呈现在 UIview 中。还希望能够为用户提供将数据存储在设备上的选项,以便也可以离线查看。我想知道直接存储 json 数据是否比创建对象然后使用 NSCoding + NSKeyedArchiver 保存更好或更差的选择。我假设按原样存储 json 字符串的优点是它在磁盘上占用的空间比归档对象少,而另一方面,通过存储归档对象,您不必每次都解析存储的数据使用更少的内存。

是否有最佳的整体选择?有没有关于这个问题的最佳实践? json 文件大小约为 8KB。

【问题讨论】:

    标签: iphone json ios nscoding storing-data


    【解决方案1】:

    我使用不同的方法。在我的应用程序中解析 JSON 数据后,它就会存储在 NSDictionary 中。我将其保留为 .plist 文件。

    [myDictionary writeToFile:[self saveFilePath] atomically:YES];
    

    加载:

    NSMutableDictionary *wholeDictionary = [NSDictionary dictionaryWithContentsOfFile:[self saveFilePath]];
    

    就是这样!

    【讨论】:

    • 这似乎是一种简单而有效的方法。谢谢!它使用的磁盘空间是否比归档对象少?
    • @Kremk:它可能使用相同或更多的空间。 plist 格式不是特别节省空间,因为它是一种人类可读的 XML 格式。密钥存档可能会以二进制格式存储一些内容(说“可能”,因为我没有检查过),这将为您节省一些空间。
    • 我同意@JeremyP,但鉴于它们是 8Kb 文件,不值得付出更多努力。
    • @Hiltmon 我可以存储嵌套对象吗?即具有多个对象的数组&这个对象可能是具有多个键的字典,其中一个键值是数组。你怎么看?
    • @Ajay Sharma:Yes.Try this & then see your app's Documents dir: NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:4], @" firstKey", @"secondValue", @"secondKey",nil], [NSArray arrayWithObjects:@"1",@"2", nil] ,nil], @"rootKey", nil]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; [dict writeToFile:[NSString stringWithFormat:@"%@/data.plist", documentsDirectory] ​​原子:YES];
    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 2018-12-17
    • 2012-12-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多