写/阅读plist文件iPhone
问题描述:
我有我的iPhone应用程序中的plist,我想读取和写入从我的单一整数,并形成它。写/阅读plist文件iPhone
我有这个来阅读:
scoreData *score = [scoreData sharedData];
filePath = @"stats.plist";
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
score.highScore = [plistDict objectForKey:@"score"];
然后写它:
scoreData *score = [scoreData sharedData];
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
[plistDict setValue:score.highScore forKey:@"score"];
[plistDict writeToFile:filePath atomically: YES];
我得到两个部分的错误:
转换无效形式objc_object *到int
and
无效的转换表格int到objc_object
我非常感谢任何帮助,谢谢。
答
两件事情:
当你在字典中设置一个键,you're probably after
setObject:forKey:
而不是setValue:forKey:
。字典包含对象(类型
id
或NSString*
或您自己的Obj-C对象),而不是基元类型(int,BOOL等)。
当你想存储的对象 - 收集基本类型,你可以“包装”它的对象是这样的:
[plistDict setObject:[NSNumber numberWithInt:score.highScore] forKey:@"score"];
而且拿回来这样的:
score.highScore = [[pListDict objectForKey:@"score"] intValue];
答
看看这个回答你的问题:
How to create a new custom property list in iPhone Applications
你可以使用NSUserDefaults,但当然highScore不是真的默认。
建立没有错误nw这是伟大的!但是我改变score.highScore,然后完全退出应用程序,重新启动并将其重置为零,它永远不会返回值。希望得到帮助,谢谢。 – 2010-10-17 16:34:59
有趣的发现。我认为我使用它的代码写入plist并阅读它,但实际上并没有保存它,因为我下次使用该应用程序。可能?我怎样才能解决这个问题? – 2010-10-17 17:09:24
可能不起作用,因为您正在尝试将字典写入应用程序包内的.plist文件,该文件夹是只读的。你应该检查'[plistDict writeToFile:filePath atomically:YES]的返回值;'' (YES =成功,NO =写入失败)。 尝试将文件写入App Bundle文档文件夹中的路径,该文件夹是可读写的。您可以使用获得的文件路径:NSArray的* arrayPaths = \t \t NSSearchPathForDirectoriesInDomains( \t \t \t NSDocumentDirectory, \t \t \t NSUserDomainMask, \t \t \t YES); \t NSString * docDir = [arrayPaths objectAtIndex:0]; – 2011-06-09 10:05:54