NSUserDefaults not saving in iOS 7 - iphone

I'm having this issue with NSUserDefaults. It is saving the defaults until I kill the app in the background then when I return all the defaults are gone. They are also gone every time a build a new version onto my device. But again, they are there within app so long as I don't kill it in the background. It's working fine in iOS 6. Thoughts?

Take your value in string(or any other as per your requirement) and save the string in user defaults
NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
NSString *str=[NSString stringWithFormat:#"%#",[dicUser objectForKey:#"device_token"]];
[userdefault setObject:str forKey:#"YOURKEY"];

Since you haven't your code, so i am giving example which is perfectly working for me on iOS 7, give it a try. Hopefully works for you too.
For saving boolean value
bool flag = YES;
[[NSUserDefaults standardUserDefaults] setBool:flag forKey:#"flag"];
For retrieving boolean value
bool flag = [[NSUserDefaults standardUserDefaults] boolForKey:#"flag"];

make sure few things like you have declared the userDefaults before using it and if you've taken that in you AppDelegate file then here is a sample code how i am saving values and it works fine so try it this way
APP_DELEGATE.userDefaults = [NSUserDefaults standardUserDefaults];
[APP_DELEGATE.userDefaults setObject:#"unChecked" forKey:#"CheckMark"];
[APP_DELEGATE.userDefaults synchronize];
here APP_DELEGATE is declared like this in my AppDelegate.h file
#define APP_DELEGATE ((AppDelegate*)[[UIApplication sharedApplication] delegate])
hope it helps!

Related

Strange iPhone SDK NSUserDefaults behaviour

I'm experiencing some strange NSUserDefaults behaviour. I save my data, then synchronize, then do a NSlog of the NSUserDefaults to make sure its saved. The data is shown as saved properly from the NSlog, but when I completely close the app (double click home button and kill the app) when it restarts the value has not changed. Whats even stranger is if I repeat the code several times by saving NSUserDefaults, killing the app, reloading the NSUserDefaults sometimes it gets saved properly and other times it does not.
I read this post Strange NSUserDefaults behavior but I am calling synchronize so I don't think thats my problem.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:#"MyString" forKey:#"testString"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
Any help is greatly appreciated.
What really confuses me is if the NSLog of standardUserDefaults shows the data is saved why wouldn't it be after the app has been killed???
Thanks
UPDATE
Looks like the issue was with a mixup in mutable and immutable arrays i was saving to NSUserDefaults. I used mutablecopy when I was retrieving the data and seemed to solve the issue.
For getting the value you could use something like this
NSUserDEfaults *ud = [NSUserDefault standarUserDefaults];
[ud objectForKey=#"YourKey"];
If it returns nil it hasn't been saved.

NSUserDefaults giving error

I am using NSUserDefaults in my application. It was working fine until i was having ios 4.3 and xcode 4.0. But now i have updated to ios 5 and xcode 4.2...
It's giving error!
NSString *storedLanguage = [[NSUserDefaults standardUserDefaults] objectForKey:#"language"];
*** -[NSUserDefaults objectForKey:]: message sent to deallocated instance 0x26e800
I don't know how to resolve it..i have tried all my effort!
Any help will be appreciated!
Thanks
Well from your question its looking like early release of some object.
Cant say where is the problem.
But give a try to this one
NSUserDefaults *defaults = [[NSUserDefaults standardUserDefaults] retain];
NSString * storedLanguage = [NSString stringWithFormat:#"%#",[defaults objectForKey:#"language"]];
[defaults release];
=============================== OR ================================
This one
NSString *sessionId=[NSString stringWithFormat:#"%#",[[NSUserDefaults standardUserDefaults]valueForKey:#"language"]];
They might help you...
Cheers
Please do the same thing said by Naved but with little modification.
NSUserDefaults *defaults = [[NSUserDefaults standardUserDefaults] retain];
NSString * storedLanguage = [defaults objectForKey:#"language"];
[defaults release];
Use a different key for your settings that doesn't collide with reserved (existing but inaccessible) setting names. (e.g. "MyUsersLanguageSettingsKey")
It's working fine now.. Actually there is one thing in ios5. If you release your nsdefaults in one class, you can't use anywhere in the application..
I was releasing the NSDefaults in my appdelegate file. so it was not working in other classes..But it was working in ios4.. I don't know why it was working here?
Thanks to all for giving time!!

How to save variables after application shut down?

I want to save some integers after application shut down and restore them after application opening, what is the easiest way to do this?
You should store and load data from NSUserDefaults:
http://developer.apple.com/library/IOS/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// to store
[defaults setObject:[NSNumber numberWithInt:12345] forKey:#"myKey"];
[defaults synchronize];
// to load
NSNumber *aNumber = [defaults objectForKey:#"myKey"];
NSInteger anInt = [aNumber intValue];
Check out the NSUserDefaults documentation. You can set arbitrary key-value pairs there which (as long as you call the shared user defaults object’s -synchronize at some point before your app terminates) will persist between launches.
You can save them in the NSUserDefaults. This is mainly used for preferences.
[[NSUserDefaults standardUserDefaults] setObject:someInteger forKey:#"someIntegerKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
You can also save them to a Property List file if you have more data you'd like to store.
NSDictionary *someDictionary = [NSDictionary dictionaryWithObjectsAndKeys:someInt1, #"someIntKey1", someInt2, #"someIntKey2", nil];
[someDictionary writeToFile:somePath error:&error];
To save upon exiting the app place any code in
- (void)applicationWillTerminate:(UIApplication *)application
Look into using NSUserDefaults. This works like a dictionary that you can add key/value pairs to. You save the variables in your app delegate's applicationWillTerminate and applicationDidEnterBackground methods. You load the variables again in applicationDidFinishLoading.
The easiest way is to use NSUserDefaults. Your app delegate will get an -applicationWillTerminate: message when the app is about to shut down, and you can write your data to NSUserDefaults (or write it into your own file if the amount of data is large). Then, when your app starts up again, your app delegate will get an -applicationDidFinishLaunching, and you can read your data back again.
Serialize them and store them on memory. You have to do this before shut down and load when app is reopened

Storing preferences that ship with the iPhone without a Settings App

I want to ship my iPhone app with some preferences but I don't need to create a "Settings App" using a plist and all that. I would like to do this using NSUserDefaults and know how to store and retrieve using this class. However, I'm struggling with how to have an initial set of preferences there when the user loads the app for the first time. Should I retrieve my NSUserDefaults in ViewDidLoad and if they return nil, set them at that point? Or is there a better method?
I'd do it like you proposed. Check whether the user default keys do exist already and if not, create them using default values.
Where you do this check is up to you, but of course it should happen before any part of your app actually needs some of the info. So, like mbehan suggested, you might want to perform that init check within didFinishLaunching of your appdelegate.
There's a method for that:
[[NSUserDefaults standardUserDefaults] registerDefaults:aDictionary];
The method takes a dictionary of keys/values for NSUserDefaults to use if the user hasn't set anything more specific.
You need to call this every time the app starts. Apple suggest:
The contents of the registration domain are not written to disk; you need to call this method each time your application starts. You can place a plist file in the application's Resources directory and call registerDefaults: with the contents that you read in from that file.
I spent some time reviewing the iPhone documentation and multiple posts. I think the following is adequate for most purposes if you do not want to create settings for your app in the Settings application.
Here is a code snippet that you can drop in AppDelegate didFinishLaunching:
NSString *test = #"Test";
NSString *testKey = #"TestKey";
NSString *test2 = #"Test2";
NSString *test2Key = #"Test2Key";
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:test,testKey,test2,test2Key,nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dict];
/*
Alternative if we want to create default values in a file called Defaults.plist in Resources folder
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Defaults" ofType:#"plist"]]];
To set the preference within the app:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:#"MyNewTest" forKey:#"TestKey"];
To retrieve the preference within the app:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *results = [defaults stringForKey:#"TestKey"];
Can also use the following syntax:
intForKey:
floatForKey:
boolForKey:
objectForKey:
Returns Objective-C object like NSString, NDDate, or NSNumber
If the object is not a string, may need to specify the value, such as
Label.text = [[defaults objectForKey:#"TestPreferenceStoredAsNumber"]stringValue];
*/
Place the following in AppDelegate applicationWillTerminate and applicationDidEnterBackground:
[[NSUserDefaults standardUserDefaults]synchronize];
Then to view the preferences, place this code in a convenient spot:
// View all keys and values in Console
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);

Why is NSUserDefaults not saving my values?

Hi I am trying to use NSUserDefaults to save some default values in database. I am able to save the values in the NSUserDefaults (even checked it in NSLog).
Now I need the values in app delegate when the application is restarted. But I am not getting anything in the NSUserDefaults. Following is my code from my class where I save the values in NSUserDefaults:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:appDel.dictProfile forKey:#"dict"];
NSLog(#"%#",[prefs valueForKey:#"dict"]);
Following is my code from App Delegagte:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSLog(#"%#",[prefs valueForKey:#"dict"]);
the above code always returns me null.
Can some one please help me?
If you terminate your app by pressing the home button (in the Simulator or on the device), your NSUserDefaults will get saved.
If you terminate your app by pressing "Stop" in Xcode (in the Simulator or on the device), your NSUserDefaults might get saved, but there's a good chance they won't. NSUserDefaults persists any changes periodically, and if you terminate the process before they've been persisted, they'll be gone. You can force the save by calling:
[[NSUserDefaults standardUserDefaults] synchronize];
Addendum:
In iOS4 (this answer was originally written when iOS3 was the public release), your NSUserDefaults may not get saved when pressing the home button. Manually calling [[NSUserDefaults standardUserDefaults] synchronize] in applicationDidEnterBackground: should ensure that your NSUserDefaults are saved correctly (this should really be a built-in behaviour IMO).
This code works fine for me .
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setObject:myString forKey:#"Prefs"];
[standardUserDefaults synchronize];
}
You didn't say whether you are running on a device or in the simulator, but if you restart the application in the simulator, all preferences will be reset between launches if you launch from Xcode. The preferences will only be preserved if you relaunch from the simulator itself.
In my case I was saving and retrieving a string. When I synchronized after saving and then retrived in another thread, it was not working properly. The problem was solved by synchronizing both after saving and before retreiving.