PDA

View Full Version : Help with NSUserDefaults




Jeremy1026
Sep 24, 2008, 08:39 AM
So, I figured out how to pull NSUserDefaults using a settings bundle. But I am trying to do it without a bundle. I just want to save a variable called "theLevel" at a defined point. Then call that variable at the launch (or awakeFromNib) of the application. Can anyone help me with this?



Jeremy1026
Sep 24, 2008, 12:26 PM
Alright, so I am able to store the value (converted from an int to a string.) It gets saved in my applications preference folder in "com.yourcompany.ChainAttraction.plist" But I am having problems reading that value?

Here is the code I am trying to use to save and load.

-(void)saveToUserDefaults:(NSString*)levelString
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

if (standardUserDefaults) {
[standardUserDefaults setObject:levelString forKey:@"highlevel"];
[standardUserDefaults synchronize];
}
}

-(NSString*)retrieveFromUserDefaults
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *val = nil;

if (standardUserDefaults)
val = [standardUserDefaults objectForKey:@"highlevel"];

return val;
}

I modified the code found at http://www.cocoadev.com/index.pl?NSUserDefaults

Jeremy1026
Sep 24, 2008, 12:31 PM
GOT IT GOT IT! I don't know why that code was going through the trouble of the if statement...anywho.

Simlpy use
NSString *val = [standardUserDefaults objectForKey:@"theKey"]; to pull the value.