-1

Can somebody tell me what's wrong with that piece of code :

    NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"scores" ofType:@"plist"];
    NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];

    NSMutableDictionary *userDict = [[NSMutableDictionary alloc] init];
    [userDict setValue:firstname forKey:@"firstname"];
    [userDict setValue:[NSNumber numberWithInt:0 ] forKey:@"successes"];
    [userDict setValue:[NSNumber numberWithInt:0 ] forKey:@"fails"];
    [data insertObject:userDict atIndex:0];
    [data writeToFile:plistPath atomically:YES];

    [userDict release];
    [data release];

The scores.plist is added to my project (Supporting Files) and look like this

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>

</array>
</plist>

Thanks

Titouan de Bailleul
  • 12,920
  • 11
  • 66
  • 121

1 Answers1

1

You should use -setObject:forKey: instead of -setValue:forKey:. The latter is for KVC and while it usually works, it does so by sending -setObject:forKey: for most keys.

The main issue with your code that I can see is that you save userDict to scores.plist and then immediately overwrite it.

Also, you are trying to write into the application's bundle. This is definitely not allowed on iOS and may fail on OS X depending on permissions. See this question:

NSMutableArray writeToFile:atomically always returns NO on device but works fine on simulator

Community
  • 1
  • 1
JeremyP
  • 84,577
  • 15
  • 123
  • 161