Write/Read plist file iPhone

无人久伴 提交于 2019-12-04 09:38:51

问题


I have plist in my iphone app and I want to read and write an integer from my single to and form it.

I have this to read it:

 scoreData *score = [scoreData sharedData];

 filePath = @"stats.plist";
 NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

 score.highScore = [plistDict objectForKey:@"score"];

Then to write to it:

scoreData *score = [scoreData sharedData];

 NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

 [plistDict setValue:score.highScore forKey:@"score"];
 [plistDict writeToFile:filePath atomically: YES];

I am getting an error in both parts:

Invalid conversion form objc_object* to int

and

Invalid conversion form int to objc_object

I appreciate any help, thanks.


回答1:


Two things:

  1. When you're setting a key in a dictionary, you're probably after setObject:forKey: instead of setValue:forKey:.

  2. Dictionaries hold objects (type id or NSString* or your own Obj-C objects), not primitive types (int, BOOL, etc).

When you want to store a primitive type in an Obj-C collection, you can "wrap" it in an object like this:

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

And get it back like this:

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



回答2:


See if this answers your question:

How to create a new custom property list in iPhone Applications

You could use NSUserDefaults but of course highScore isn't really a default.



来源:https://stackoverflow.com/questions/3954020/write-read-plist-file-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!