有人可以告诉我这段代码有什么问题:
NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"scores" ofType:@"plist"];
NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
NSMutableDictionary *userDict = [[NSMutableDictionary alloc] init];
[userDict setValue:firstname forKey:@"firstname"];
[userDict setValue:[NSNumber numberWithInt:0 ] forKey:@"successes"];
[userDict setValue:[NSNumber numberWithInt:0 ] forKey:@"fails"];
[data insertObject:userDict atIndex:0];
[data writeToFile:plistPath atomically:YES];
[userDict release];
[data release];
得分.plist已添加到我的项目(支持文件)中,看起来像这样
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
</array>
</plist>
由于
答案 0 :(得分:1)
您应该使用-setObject:forKey:
代替-setValue:forKey:
。后者适用于KVC,虽然它通常有效,但它通过为大多数密钥发送-setObject:forKey:
来实现。
我可以看到您的代码的主要问题是您将userDict保存到scores.plist,然后立即覆盖它。
此外,您正在尝试写入应用程序的包。这绝对不允许在iOS上,并且可能在OS X上失败,具体取决于权限。看到这个问题:
NSMutableArray writeToFile:atomically always returns NO on device but works fine on simulator