2018 年 reading/writing NSDictionary 和 NSArray 到 Objective-C 文件的正确方法是什么?

What is the proper way of reading/writing NSDictionary and NSArray to a file in Objective-C in 2018?

以下 NSDictionary 方法及其等效的 NSArray 文件交互方法已弃用:

[NSDictionary dictionaryWithContentsOfURL:]

[NSDictionary dictionaryWithContentsOfFile:]

[NSDictionary initWithContentsOfFile:]

还有

[NSDictionary writeToFile:atomically:]

[NSDictionary writeToURL:atomically:]


我应该用什么来将 dictionary/array 存储在 Objective C 中?

它不是很简洁,但是你可以使用NSPropertyListSerialization的class方法在plist对象(包括NSArray和NSDictionary)和NSData之间转换,然后使用NSData的API读取和从文件写入。

例如,从文件中读入可能如下所示:

NSData *fileData = [NSData dataWithContentsOfFile:@"foo"];
NSError *error = nil;
NSDictionary *dict = [NSPropertyListSerialization propertyListWithData:fileData options:NSPropertyListImmutable format:NULL error:&error];
NSAssert([dict isKindOfClass:[NSDictionary class]], @"Should have read a dictionary object");
NSAssert(error == nil, @"Should not have encountered an error");

同样,写入文件也是类似的,只是两个步骤相反:

NSError *error;
NSData *data = [NSPropertyListSerialization dataWithPropertyList:dict format:NSPropertyListXMLFormat_v1_0 options:0 error:&error];
NSAssert(error == nil, @"Should not have encountered an error");
[data writeToFile:@"foo" atomically:YES];

虽然这需要更多的击键来编写,但是…

  • 更能表达实际发生的过程(转换,然后文件 I/O)
  • 更清楚文件中的实际内容 foo(属性 以 XML v1.0 格式列出数据)
  • 调试时更有帮助(输出 error 指针给出失败原因;NSData 有 I/O 以及其他更详细的方法)

来自NSDictionary.h中的评论:

These methods are deprecated, and will be marked with API_DEPRECATED in a subsequent release. Use the variants that use errors instead.

使用错误的变体是

- (nullable NSDictionary<NSString *, ObjectType> *)initWithContentsOfURL:(NSURL *)url error:(NSError **)error;
+ (nullable NSDictionary<NSString *, ObjectType> *)dictionaryWithContentsOfURL:(NSURL *)url error:(NSError **)error;

- (BOOL)writeToURL:(NSURL *)url error:(NSError **)error;

Serializes this instance to the specified URL in the NSPropertyList format (using NSPropertyListXMLFormat_v1_0). For other formats use NSPropertyListSerialization directly.