【问题标题】:Differences with archiveRootObject:toFile: and writeToFile:与 archiveRootObject:toFile: 和 writeToFile 的区别:
【发布时间】:2013-04-11 05:28:07
【问题描述】:

最近,我正在学习 NSKeyedArchiver 和 NSKeyedUnarchiver。我发现有三种方法可以归档数组,我正在尝试找出其中的区别。

1.使用archiveRootObject:toFile:

    [NSKeyedArchiver archiveRootObject:testArray toFile:filePath];

2.从archivedDataWithRootObject:获取数据并写入文件

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:testArray];
    [data writeToFile:filePath atomically:YES];

3.使用encodeObject:获取数据

    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:testArray forKey:@"testArray"];
    [archiver finishEncoding];
    [data writeToFile:path atomically:YES];

经过测试,我发现上述所有方法都可以正常工作,并且可以将相同的内容写入文件。

Q1:以上所有方式有什么区别?

Q2:我可以在第 3 种方式中使用 NSData 吗?

【问题讨论】:

    标签: ios objective-c nskeyedarchiver


    【解决方案1】:

    第一个不会让您选择如何处理数据。它将转到一个文件。例如,我使用第二种方式通过网络连接发送数据。它更灵活。第三种方式做同样的事情,除了你可以把单个对象放进去。我不确定它是否可以与现有的数组一起使用,但它可能会。它更加灵活,因此您无需准备好数组或字典。

    差不多就是这样。一切都关乎便利性与灵活性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-21
      • 2011-02-01
      • 2012-02-27
      • 2013-10-29
      • 2018-06-21
      • 1970-01-01
      相关资源
      最近更新 更多