Reputation: 38940
I have a flipView application. On the FlipView I keep settings for the MainView and would like to use NSUserDefaults to store 2 integers for the MainView. I will use those integers in the main application. Is there some basic code that can implement what I'm trying to do?
I'd like to store the information on the FlipView (if changed) and have a default setting when the program is first run in the MainView.
Also, will I need to release
the NSUserDefaults object once I'm finished using it?
Upvotes: 0
Views: 456
Reputation: 4215
You can store the integer with [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"theKey"] and retrive it with [[NSUserDefaults standardUserDefautls] integerForKey:@"theKey"]. That's really all you need to handle an integer with user defaults.
You don't release the NSUserDefaults object. It's a singleton, so only one will be created for the life of your app. You also don't own it which means you wouldn't be releasing it.
Upvotes: 1
Reputation: 8804
check out below code, I had wrapped and make easy for you,
you can use below codes by: import "Settings.h" in any code where you want to use, (maybe AppDelegate.m) in your case. then
to set value, use
[Settings setSetting:@"AUTOLOGIN" value:@"1"];
[Settings setSetting:@"OTHERPROPERTY" value:@"100"];
and remember that, store pointer datatype only,
to get setting value:
[Settings getSetting:@"AUTOLOGIN"];
here below there are two files, Setting.h and Setting.m , make those
header file is :
#import <Foundation/Foundation.h>
@interface Settings : NSObject {
}
+(id) getSetting:(NSString *)key;
+(void) setSetting:(NSString *)key value:(id)v;
@end
- and implementation file is
#import "Settings.h"
@implementation GCCSettings
static NSMutableDictionary *settings = nil;
+(id) getSetting:(NSString *)key{
if(settings == nil){
settings = [[NSMutableDictionary alloc] initWithDictionary:
[[NSUserDefaults standardUserDefaults] dictionaryForKey:@"settings"]
];
}
return [settings objectForKey:key];
}
+(void) setSetting:(NSString *)key value:(id)v{
[settings setValue:v forKey:key];
[[NSUserDefaults standardUserDefaults] setObject:settings forKey:@"settings"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
@end
and finally don't release any objects, which you had not allocated using(new, init, retain etc).
Upvotes: 2