【问题标题】:NSUserDefaults vs NSCodingNSUserDefaults 与 NSCoding
【发布时间】:2014-04-11 17:19:06
【问题描述】:

从我的应用程序中保存少量数据时,使用NSUserDefaults 还是NSCoding 更好? 现在我使用NSCoding(encodeWithCoder/initWithCoder 等),但似乎NSUserDefaults 可能更简单。 我的总数据大概是各种Ints/Strings/MutableArray,总共也就几十个左右。

【问题讨论】:

  • 你在比较苹果和橘子。您可能会使用 NSCoding 将某些内容保存到 NSUserDefaults 中,那么您要绘制什么对比?
  • 听起来你想要的是NSPropertyListSerialization
  • matt 进一步指出,NSCoding 根本不是一种存储机制。你在用你的编码数据做什么?这就是您应该与使用 NSUserDefaults 进行比较的内容。

标签: ios objective-c nsuserdefaults nscoding


【解决方案1】:

我假设NSCoding 的意思是“在使用NSCoding API 序列化对象后将对象保存到文件中”。尽管这两种方法都适用于原始数据类型,但一旦您开始序列化具有复杂结构的对象,NSUserDefaults 方法就会变得更加困难。

相比之下,将NSCoding 类的数据保存到文件在对象结构方面提供了高度的灵活性。如果您知道将来不需要这种灵活性,请选择NSUserDefaults;如果您不确定,请保留这些文件。

【讨论】:

  • 是的,你的假设是正确的(我的问题应该说得更清楚)。我会坚持使用 NSCoding/file 方法,因为它已经在工作了。谢谢。
【解决方案2】:

我更喜欢使用以编程方式创建的 plist 文件

NSString *appFile;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    appFile = [documentsDirectory stringByAppendingPathComponent:@"myFile"];
    //this creates the file path


    NSDictionary* tempDict = [[NSDictionary alloc]initWithContentsOfFile:appFile];
    //this gets the data from storage

    [tempDict writeToFile:appFile atomically:YES];
    //this updates the data to storage

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 2014-11-18
    相关资源
    最近更新 更多