对象有效时,NSDictionary writeToFile失败,权限为0k

Aiv*_*nF. 3 macos file objective-c nsdictionary

为什么NSDictionary不能写?我已经检查了字典的内容:所有实例都是NSString和的NSNumber。我检查了权限:在相同路径下具有相同名称的文本文件写得很好。当然,我的字典不是空的。

NSString *file = ...
NSDictionary *dict = ...

// check dictionary keys
BOOL wrong = NO;
for (id num in [dict allKeys]) {
    if (![num isKindOfClass:[NSNumber class]]) {
        wrong = YES;
        break;
    }
}
if (wrong) {
    NSLog(@"First");
}
// check dictionary values
wrong = NO;
for (id num in [dict allValues]) {
    if (![num isKindOfClass:[NSString class]]) {
        wrong = YES;
        break;
    }
}
if (wrong) {
    NSLog(@"Second");
}

if (![dict writeToFile:file atomically:YES]) {
    // 0k, let's try to create a text file
    NSLog(@"Names writing error!");
    [@"Something here... .. ." writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
Run Code Online (Sandbox Code Playgroud)

输出:“名称写入错误!”
文本文件创建成功。

vad*_*ian 5

写出字典会创建一个属性列表,并且根据文档,属性列表中的所有键都必须是string

...尽管NSDictionary和CFDictionary对象允许它们的键成为任何类型的对象,但是如果键不是字符串对象,则集合不是属性列表对象。

NSNumber 不支持将对象作为键。