i have been working on a app, and needed to store a string. I used this code to set the default:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:CertificateKey.stringValue forKey:#"SavedKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"%#",[defaults objectForKey:#"SavedKey"]);
I loged it, so i know it saved...well, it showed me the value.
When i open my application, I use this to retrieve the default:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[CertificateKey setStringValue:[defaults objectForKey:#"SavedKey"]];
[CertificateKey setTitleWithMnemonic:[defaults objectForKey:#"SavedKey"]];
[[NSUserDefaults standardUserDefaults] synchronize];
Why will it not get the default value? Did i not completely save it?
Don't quit the application by pressing the stop button in xcode. Instead, quit it by right clicking on the application icon and selecting "Quit".
Edit
Maybe the first time that you execute the application, you want to save some defaults but you don't want to set them the second+ time that the application runs.
For this purpose in some class initialize method register the defaults, like this:
+ (void) initialize
{
NSUserDefaults* defaults= [NSUserDefaults standardUserDefaults];
[defaults registerDefaults: #{} ];
// This case it's an empty dictionary, but you can put whatever you want inside it.
// just convert it to data if it's not an object storable to a plist file.
}
Also, you're using setValue:forKey: , that method is inherited from NSObject. Use setObject:forKey: .
And use finalize if you want to save the defaults at the end:
- (void) finalize
{
// Save the defaults here
}
You might have a problem because you are creating an instance of NSUserDefaults. From what I understand you are supposed to access it like so: [[NSUserDefaults standardUserDefaults] setValue:#"Pikachu" forKey:#"Best Pokemon Ever"]; [[NSUserDefaults standardDefaults] objectForKey:#"Best Pokemon Ever"]; Rather than actually creating an instance of it.
Related
I have a check box type application, kinda like notes on the iPhone. When the user closes the application and double tabs the home button and deletes the application from the background, the things they have typed also get deleted or reset. I was thinking of calling
[self saveContext];
But that didn't work. WHat should I be calling?
You can usual use something such as NSUserDefaults to save information. Or, you can go another route and save the information in a data structure and write that to a file. There are many easy ways of doing this. For instance, if you want to preserve a checked value, you could do the following:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:YES forKey:"checked"];
[defaults synchronize];
Very simple, and then can be queried across app exits, like so:
if( [defaults boolForKey:"checked"] ) {
//do stuff here
}
I've been banging my head against the wall for several days trying to understand how to perform an action as soon as the application starts.
Basically I want to download a plist from my website if the user turns on a switch that determines if he wants to download new contents at startup.
Point is that:
"A" class has the method to reload the contents;
"B" class has the switch that, if turned on, tells the delegate to perform the reload contents method as soon as the application starts
Now, I don't know how to tell the AppDelegate to run the method of class "A" if the switch of class "B" is turned on. Obviously I need to use NSUserDefaults, but i'm pretty lost after that.
Can anyone make things clearer? Or, is there a more comfortable workaround to do it?
yes you can do this using NSUserDefaults
in your class b.
-(void)swithChanged
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//check if !null
if(![[defaults objectForKey:#"shouldDownload"]isKindOfClass:[NSNull class]]){
if([(NSNumber*)[defaults objectForKey:#"shouldDownload"]boolValue])
{
[defaults setObject:[NSNumber numberWithInt:0] forKey:#"shouldDownload"];
[defaults synchronize];
}else{
[defaults setObject:[NSNumber numberWithInt:1] forKey:#"shouldDownload"];
[defaults synchronize];
}
}else{
//set your NSUserDefault here for the first time
}
}
in your AppDelegate
- (void)applicationDidBecomeActive:(UIApplication *)application{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//check if !null
if(![[defaults objectForKey:#"shouldDownload"]isKindOfClass:[NSNull class]]){
if([(NSNumber*)[defaults objectForKey:#"shouldDownload"]boolValue])
{
//you can write the downloadData method in this appDelegate,
//[self downloadData]
//OR
AClass *aClass = [AClass alloc]init];
[aClass downloadData];
}else{
//do not download
}
}else{
//the default behaviour of app, download or not?
}
}
Here's a post that could help you understand the flows during application start-up:
http://www.cocoanetics.com/2010/07/understanding-ios-4-backgrounding-and-delegate-messaging
Also, check this post:
applicationWillEnterForeground vs. applicationDidBecomeActive, applicationWillResignActive vs. applicationDidEnterBackground
This is supposed to save the value of two UISwitches to NSUserDefaults and then set the switches on load based on the values saved to the defaults. I've been at this for hours but I can't seem to get it to work. Any help would be greatly appreciated.
The toggles are in a View that I'm using for settings. There are only two toggles, so I want to use NSUserDefaults. Toggles default to OFF. I want to toggle to ON and have that change be saved so that I can change the User experience based on the toggle's value. Then, when the User opens the settings again, I want them to display their current saved state.
I think that the value is being saved, but it is not being applied to the Switches when I reenter the Settings View.
- (IBAction)setBeadVibratorBySwitchState:(id)sender
{
if (setBeadVibrator.selected == YES) {
NSUserDefaults *beadSettings = [NSUserDefaults standardUserDefaults];
[beadSettings setBool:NO forKey:#"beadSwitchStatus"];
[beadSettings synchronize];
}
if (setBeadVibrator.selected == NO) {
NSUserDefaults *beadSettings = [NSUserDefaults standardUserDefaults];
[beadSettings setBool:YES forKey:#"beadSwitchStatus"];
[beadSettings synchronize];
}
NSLog(#"Bead Executed");
}
- (IBAction)setDecadeVibratorBySwitchState:(id)sender
{
if (setDecadeVibrator.selected == YES) {
NSUserDefaults *decadeSettings = [NSUserDefaults standardUserDefaults];
[decadeSettings setBool:NO forKey:#"decadeSwitchStatus"];
[decadeSettings synchronize];
}
if (setDecadeVibrator.selected == NO){
NSUserDefaults *decadeSettings = [NSUserDefaults standardUserDefaults];
[decadeSettings setBool:YES forKey:#"decadeSwitchStatus"];
[decadeSettings synchronize];
}
NSLog(#"Decade Executed");
}
- (void)viewDidLoad
{
[super viewDidLoad];
setBeadVibrator.selected = [[NSUserDefaults standardUserDefaults] boolForKey:#"beadSwitchStatus"];
setDecadeVibrator.selected = [[NSUserDefaults standardUserDefaults] boolForKey:#"decadeSwitchStatus"];
}
NSUserDefaults can only store objects of type NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. So, I suggest that you put the state of the switch in an NSString and put that string in the NSUserDefaults. Than when you retrieve the info from the NSUserDefaults, you can use an if statement to set the value of the boolean again.
If you are using UISwitch, you should set the on property, instead of selected.
setBeadVibrator.on = [[NSUserDefaults standardUserDefaults] boolForKey:#"beadSwitchStatus"];
setDecadeVibrator.on = [[NSUserDefaults standardUserDefaults] boolForKey:#"decadeSwitchStatus"];
see UISwitch Class Reference
I would suggest that you put the NSLog statements in the if-statements to see if they are really saved. If not, your UISwitches may not be configured properly with the UIControlEventValueChanged event.
You can read up more from Apple doc. Here is a very detailed website on using UISwitches.
How would I check if it is the first launch of of my application using NSUserDefaults and running some code for the first time my app opens?
This should point you in the right direction:
static NSString* const hasRunAppOnceKey = #"hasRunAppOnceKey";
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if ([defaults boolForKey:hasRunAppOnceKey] == NO)
{
// Some code you want to run on first use...
[defaults setBool:YES forKey:hasRunAppOnceKey];
}
The NSUserDefaults answer is the first thing that popped in my head, but upon reflection I will make another suggestion. A bit more work, but it's worth considering. The motive is: sometimes when troubleshooting an app, Apple recommends deleting that app's plist file. It's a fairly ubiquitous troubleshooting technique. I would recommend storing your boolean in your plist file instead of NSUserDefaults.
Disclaimer: I only do iOS development, so I'm not sure how NSUserDefaults and plists interact on the Mac, and I don't know what all is involved in getting your plist to live in ~/Library/Application\ Support/Preferences/com.mycompany.MyAppName.plist
Anyway, I imagine what this requires is having some code which can actually author a "fresh" plist (probably a copy from a template file in your bundle), and you app does this if it launches and does not see a plist. The default plist should not include the flag which lets your users skip the 'first time' code, but if they have opened the app before, and then delete the plist, they should get default behavior back.
This is an important behavior to support where possible, to aide our users if our app ever gives them trouble.
if (![[NSUserDefaults standardUserDefaults] boolForKey:#"hasBeenLaunched"]) {
// Run code on the first launch only ...
[defaults setBool:YES forKey:#"hasBeenLaunched"];
}
You can use NSUserDefaults to save bools, integers, objects into the program and have them available whenever you open it. You can use 'boolForKey' to set a flag called "hasBeenLaunched". By default, this value will be NO when not set. Once you change it to YES, the code in the if condition will never be executed again.
In your main controller class, implement something like this:
static NSString * const MDFirstRunKey = #"MDFirstRun";
#implementation MDAppController
+ (void)initialize {
NSMutableDictionary *defaults = [NSMutableDictionary dictionary];
[defaults setObject:[NSNumber numberWithBool:YES] forKey:MDFirstRunKey];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
// the following if on Mac and is necessary:
[[NSUserDefaultsController sharedUserDefaultsController] setInitialValues:defaults];
}
- (void)applicationDidFinishLaunching:(NSNotification *)notification {
BOOL firstRun = [[[NSUserDefaults standardUserDefaults]
objectForKey:MDFirstRunKey] boolValue];
if (firstRun) {
// do something
[[NSUserDefaults standardUserDefaults] setObject:
[NSNumber numberWithBool:NO] forKey:MDFirstRunKey];
} else {
// do something else
}
}
#end
The +initialize class method is called before an instance of the class it's found in is created; in other words, it is called very early on, and is a good place to set up your default values.
See Preferences and Settings Programming Guide: Registering Your App's Default Preferences for more info.
I'm having a problem with NSUserDefaults. I'm saving a name, then trying to access it later in the code from another view controller, but it seems that my key is empty or not saved as when I display the string from the key my label is blank.
-(void) saveName {
NSString *name = nameField.text;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:name forKey:#"playersName"];
[defaults synchronize];
}
-(void) viewDidLoad // method called later on in code from different viewcontroller
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *name = [defaults objectForKey:#"playersName"];
playerName.text = name; // player name == myLabel
if ([[NSUsersDefaults standardUserDefaults] objectForKey:#"playersName"] == nil) {
playerName.text =#" blank";
}
}
My string doesn't seem to be saving to userdefaults as the #"blank" string keeps showing up with my label. I'm not too familiar with NSUserDefaults so any help is much appreciated.
A few things to note when using NSUserDefaults:
calls to syncrhonize method is not necesary and will only make it slower if your program is multi threaded.
Check if the key that you use is being used by other libraries in your project
Check if the value that you set to the key is not nil
Try to use stringForKey: or boolForKey: instead of objectForKey:
I had troubles a few times with NSUserDefaults but in the end it's usually my code that's problematic.
I would suggest you to check whether your '(void) saveName' method is being called or not... Put some breakpoint and see the result