为什么 NSMutableDictionary 不想写入文件?
- (void)viewDidLoad
{
[super viewDidLoad];
if ([[NSFileManager defaultManager] fileExistsAtPath:pathString])
{
infoDict = [[NSMutableDictionary alloc] initWithContentsOfFile:pathString];
}
else
{
infoDict = [[NSMutableDictionary alloc]initWithObjects:[NSArray arrayWithObjects:@"BeginFrame",@"EndFrame", nil] forKeys:[NSArray arrayWithObjects:[NSNumber numberWithBool:YES],[NSNumber numberWithBool:YES], nil]];
if ([infoDict writeToFile:pathString atomically:YES])
{
NSLog(@"Created");
}
else
{
NSLog(@"Is not created");
NSLog(@"Path %@",pathString);
}
}
这是我的代码。我检查文件是否已创建,如果没有 - 我创建一个 NSMutableDictionary
并将其写入路径中的文件,但 writeToFile
方法返回 NO
。问题出在哪里?如果我使用 NSFileManager
创建此文件,它可以工作,但当我想编写字典时却不能。
- (void)viewDidLoad
{
[super viewDidLoad];
if ([[NSFileManager defaultManager] fileExistsAtPath:pathString])
{
infoDict = [[NSMutableDictionary alloc] initWithContentsOfFile:pathString];
}
else
{
infoDict = [[NSMutableDictionary alloc]initWithObjects:[NSArray arrayWithObjects:@"BeginFrame",@"EndFrame", nil] forKeys:[NSArray arrayWithObjects:[NSNumber numberWithBool:YES],[NSNumber numberWithBool:YES], nil]];
if ([infoDict writeToFile:pathString atomically:YES])
{
NSLog(@"Created");
}
else
{
NSLog(@"Is not created");
NSLog(@"Path %@",pathString);
}
}
This is my code. I check if file is created, if not - I create a NSMutableDictionary
and I write it to file at path, but writeToFile
method returns NO
. Where is problem? If I create this file with NSFileManager
it works, but doesn't when I want to write a dictionary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
writeToFile:atomically
仅当您调用它的字典是有效的属性列表对象时才有效(参见文档)。要使 NSDictionary 成为有效的属性列表对象,除其他外,其 键必须是字符串,但在您的示例中,键是
NSNumber
实例。writeToFile:atomically
only works if the dictionary you call it on is a valid property list object (see docs).For a
NSDictionary
to be a valid property list object, among other things, its keys must be strings, but in your example the keys areNSNumber
instances.有时你无法控制要写的内容。例如,当您要编写从服务器获取的 JSON 对象时,您无法避免使用
null
值。NSData
与这些“无效”值兼容,因此将NSArray
或NSDictionary
转换为NSData
是一种理想的方式这些案例。写:
读:
You can not control the content you are going to write sometimes. For example, you can't avoid a
null
value when you are going to write a JSON object that is gotten from a server.NSData
is compatible with these "invalid" values, so convertingNSArray
orNSDictionary
toNSData
is an ideal way in these cases.write:
read: