为什么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];
}
。我检查了权限:在同一路径上写了一个同名的文本文件。当然,我的字典不是空的。
Meta
输出:"命名写错误!"
文本文件已成功创建。
答案 0 :(得分:4)
写出字典会创建一个属性列表,根据documentation,属性列表中的所有键必须是字符串。
...虽然NSDictionary和CFDictionary对象允许其键 如果键不是字符串对象,则为任何类型的对象 集合不是属性列表对象。
NSNumber
对象不支持键。
答案 1 :(得分:2)
正如@vadian指出的那样,你不能用数字键写plist。但您可以使用NSKeyedArchiver
:
NSURL *documents = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:false error:nil];
NSURL *fileURL = [documents URLByAppendingPathComponent:@"test.plist"];
// this will not work
NSDictionary *dictionary = @{@1: @"foo", @2: @"bar"};
BOOL success = [dictionary writeToFile:fileURL.path atomically:true];
NSLog(@"plist %@", success ? @"success" : @"failure");
// this will
fileURL = [documents URLByAppendingPathComponent:@"test.bplist"];
success = [NSKeyedArchiver archiveRootObject:dictionary toFile:fileURL.path];
NSLog(@"archive %@", success ? @"success" : @"failure");
您可以使用NSKeyedUnarchiver
// to read it back
NSDictionary *dictionary2 = [NSKeyedUnarchiver unarchiveObjectWithFile:fileURL.path];
NSLog(@"dictionary2 = %@", dictionary2);
注意,您可以使用符合(并正确实现)NSCoding
的任何类来执行此操作。幸运的是,NSDictionary
已经符合。您必须确保字典中的任何对象也符合(NSString
和NSNumber
都这样做)。如果您的字典中有自定义对象,则必须使其自行适应。