2010-10-17 118 views
6

我有我的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

我非常感谢任何帮助,谢谢。

回答

7

两件事情:

  1. 当你在字典中设置一个键,you're probably aftersetObject:forKey:而不是setValue:forKey:

  2. 字典包含对象(类型idNSString*或您自己的Obj-C对象),而不是基元类型(int,BOOL等)。

当你想存储的对象 - 收集基本类型,你可以“包装”它的对象是这样的:

[plistDict setObject:[NSNumber numberWithInt:score.highScore] forKey:@"score"]; 

而且拿回来这样的:

score.highScore = [[pListDict objectForKey:@"score"] intValue]; 
+0

建立没有错误nw这是伟大的!但是我改变score.highScore,然后完全退出应用程序,重新启动并将其重置为零,它永远不会返回值。希望得到帮助,谢谢。 – 2010-10-17 16:34:59

+0

有趣的发现。我认为我使用它的代码写入plist并阅读它,但实际上并没有保存它,因为我下次使用该应用程序。可能?我怎样才能解决这个问题? – 2010-10-17 17:09:24

+0

可能不起作用,因为您正在尝试将字典写入应用程序包内的.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