Reputation: 6085
I want to retrieve an integer from a plist file, increment it, and write it back to the plist file. Inside the "Levels.plist" file is a row with the key LevelNumber
, and with a value of 1
.
I use this code to retrieve the value:
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Levels.plist" ofType:@"plist"];;
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
lvl = [[plistDict objectForKey:@"LevelNumber"]intValue];
NSLog(@"%i", [[plistDict objectForKey:@"LevelNumber"]intValue]);
When I run this, I get the console output of 0. Can someone tell me what I'm doing wrong?
Upvotes: 1
Views: 767
Reputation: 6085
What I found out was that this method is not conventional for the actual device itself. What you need to do is described here, and this website explains how to do this on the actual device
Upvotes: 0
Reputation: 22938
NSString *filePath = [[NSBundle mainBundle]
pathForResource:@"Levels.plist" ofType:@"plist"];
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc]
initWithContentsOfFile:filePath];
lvl = [[plistDict objectForKey:@"LevelNumber"]intValue];
NSLog(@"%i", [[plistDict objectForKey:@"LevelNumber"]intValue]);
My guess is that NSBundle is returning nil for the pathForResource:ofType:
call, unless you've actually named your file "Levels.plist.plist".
Keep in mind that if that method happens to return nil
, the rest of your code can still proceed. Given a nil
file path, the NSMutableDictionary
will return nil, and subsequent calls to get objects out of the dictionary will also return nil
, hence your logging call showing an output of 0.
Upvotes: 1
Reputation: 89509
Sounds like you need to do a lot of error checking along the way.
Perhaps something like this:
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Levels" ofType:@"plist"];
if(filePath)
{
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
if(plistDict)
{
NSNumber * lvlNumber = [plistDict objectForKey:@"LevelNumber"];
if(lvlNumber)
{
NSInteger lvl = [lvlNumber integerValue];
NSLog( @"current lvl is %d", lvl );
// increment the found lvl by one
lvl++;
// and update the mutable dictionary
[plistDict setObject: [NSNumber numberWithInteger: lvl] forKey: @"LevelNumber"];
// then attempt to write out the updated dictionary
BOOL success = [plistDict writeToFile: filePath atomically: YES];
if( success == NO)
{
NSLog( @"did not write out updated plistDict" );
}
} else {
NSLog( @"no LevelNumber object in the dictionary" );
}
} else {
NSLog( @"plistDict is NULL");
}
}
Upvotes: 2