Write/Read plist file iPhone
Asked Answered
W

2

6

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.

Weylin answered 17/10, 2010 at 16:1 Comment(0)
C
7

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];
Cosec answered 17/10, 2010 at 16:10 Comment(3)
Builds with no errors nw which is great! But I change score.highScore, then quit the app completely, relaunch and its back to zero, it never gets the value back. Would appreciate the help, thanks.Weylin
Interesting discovery. I think the code I am using it writing to the plist and reading it but not actually saving it for when I next use the app. Possible? How can i get around this?Weylin
Probably it doesn't work because you are trying to write the dictionary to a .plist file inside your App bundle, which is read only. You should check the returned value of '[plistDict writeToFile:filePath atomically: YES];' (YES=success, NO=write failed). Try to write the file to a path in the App Bundle documents' folder, which is read-write. You can get the documents' path using: NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES); NSString *docDir = [arrayPaths objectAtIndex:0];Accipitrine
W
0

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.

Winery answered 17/10, 2010 at 17:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.