How to check if NSUserDefaults exist - iphone

I have been looking for an answer but not really found what i am looking for.
I have an application and is using NSUserDefaults to store 'currentGameStatus' and would like to ask the following questions:
How do i check if the NSUserDefaults .plist exists? Need this to determine if i need to create it for the first time and if so fill it with default values
Where do i find it on my Mac (running simulator)? Would need to delete it to test if the first run works?

you don't check.
you register your defaults. and if you haven't saved a value the default will be used.
NSDictionary *defaultUserDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:NO], #"Foo",
#"Bar", #"Baz",
[NSNumber numberWithInteger:12], #"FooBar",
nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultUserDefaults];
and you do this every time your app launches.

The way I do it is I set a BOOL flag in NSUserDefaults if it doesn't already exist:
if(![[NSUserDefaults standardUserDefaults] boolForKey:#"firstRun"]) {
//do initialization stuff here...
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"firstRun"];
}

NSUserDefaults already exists by default. You can add to it by [[NSUserDefaults standardUserDefaults] setObject:#"object" forKey:#"key"];
You can find the NSUserDefaults .plist here

Related

NSUserDefaults standardUserDefaults setObject: forKey: not working for Multivalue preference

I am trying to do following task
[[NSUserDefaults standardUserDefaults] setObject:#"Dry" forKey:#"vesselType_preference"];
[[NSUserDefaults standardUserDefaults] synchronize];
where my "vesselType_preference" is multivalue attribute, but it is not getting effected. Please help this is working for other type of attribute but not working for multivalue type.
Thanks
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults objectForKey:#"vesselType_preference"])
{
[defaults setObject:#"Dry" forKey:#"vesselType_preference"];
}
[[NSUserDefaults standardUserDefaults] synchronize];
This should work.
NSUserDefaults can only handle objects of NSDictionary, NSData, NSArray, NSString and BOOL. (There might be another in there, not sure) If you need to store a multiple value object like an array or dictionary, I would store your settings there first, then save that to the defaults.
Your code looks fine for storing information to the user defaults. Just make sure you have your object type specified before saving. (id) will not work... or won't work properly.

How to save / Load NSUserDefaults for backup purposes?

Is this code correct to load and save NSUserDefaults.
// Load
NSDictionary *dict = [[NSUserDefaults standardUserDefaults]
dictionaryRepresentation];
// Save
NSDictionary *dict = ....
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults registerDefaults:dict];
[defaults synchronize]; << Not sure if this is needed
I'm using JSON to hold the dictionary contents and I'm having problems.
I'd just like to know if this code is correct, before I look elsewhere for my problem.
Your Load code will get you a dictionary of all the current default values.
[Note This will probably be much larger than you expect as Mac OS installs a raft of defaults, you might want to make it smaller. For example, you can limit the dictionary to just those defaults in your domain which differ from their registered default using:
NSDictionary *userDefaults = [[NSUserDefaults standardUserDefaults] persistentDomainForName:#"<your bundle identifier>"];
end note]
Your Save code probably doesn't do what you expect, it installs the values you are restoring as the defaults for those keys - so if you support "Restore to Default Settings", or something similar, then these are the values that would result. What you probably want to do it set the current value of the keys, this can be done with a simple loop:
NSDictionary *dict = ....
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
foreach(id key in dict)
[defaults setObject:[dict objectForKey:key] forKey:key];
The above code is only an outline, you may need to take care what preferences you save/restore and in what order - but all that depends on your application.
// Get
NSDictionary *dict = [[NSUserDefaults standardUserDefaults] objectForKey:#"myDictionary"];
// Set
NSDictionary *dict = ...
[[NSUserDefaults standardUserDefaults] setObject:dict forKey:#"myDictionary"];

Delete All Prefs / Core Data

I want to create a button in my application that will delete all entries in core data as well as all of the NSUserDefaults. What method would I use to do this?
This method:
[[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];
resets the defaults to the registration domain, which means that removeObjectForKey is called to all the keys. I found it from this link. Hope that helps!
Here's what I use for NSUserDefaults:
for (NSString* k in [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys])
[[NSUserDefaults standardUserDefaults] removeObjectForKey:k];

Use NSUserDefaults to access a stored object

I want to access text saved through NSUserDefaults and display it in a label that has already been defined called "name". My code is below, but it doesn't work. What should I do? Thanks for your help!
name = [[NSUserDefaults standardUserDefaults] objectForKey:#"Name"];
should be:
name.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"Name"];
First, you should register your defaults someway like this: (this is only necessary if you want to add multiple items!)
NSDictionary *defaultsDict =
[NSDictionary dictionaryWithObjectsAndKeys:#"MyName", #"defaultName", #"MyAge", #"defaultAge", nil];`
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsDict];
Now use this assuming you have a label pointer:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[label setText:[defaults stringForKey:#"defaultName"]];

Cannot read values from [NSUserDefaults standardUserDefaults] after synchronize

In the Application Delegate didFinishLaunching method, I am using the following code to build up a new NSDictionary to be used as the new settings bundle for the user:
NSNumber *testValue = (NSNumber*)[[NSUserDefaults standardUserDefaults] objectForKey:#"settingsversion"];
if (testValue == nil)
{
NSNumber *numNewDB = [NSNumber numberWithBool:NO];
NSNumber *numFirstUse = [NSNumber numberWithBool:YES];
NSDate *dateLastStatic = [NSDate date];
NSDate *dateLastMobile = [NSDate date];
NSNumber *numSettingsversion = [NSNumber numberWithFloat:1.0];
NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
numNewDB, #"newdb",
numFirstUse, #"firstuse",
numSettingsversion, #"settingsversion",
dateLastStatic, #"laststaticupdate",
dateLastMobile, #"lastmobileupdate",
nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
[[NSUserDefaults standardUserDefaults] synchronize];
}
Later in another ViewController I am trying to read back a value from that same Dictionary, saved as the NSUserDefaults - well at least I thought it would, but I don't get any valid object pointer for the desired member lastUpdate back there:
in .h file:
NSDate *lastUpdate;
in the .m file in a member function:
lastUpdate = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:#"laststaticupdate"];
Even, if I print out the content of [NSUserDefaults standardUserDefaults] I only get this:
2010-04-29 15:13:22.322 myApp[4136:207] Content of UserDefaults: <NSUserDefaults: 0x11d340>
This leads me to the conclusion that there is no standardUserDefaults dictionary somewhere in memory or it cannot be determined as such a structure.
Edit: Every time, I restart the app ión the device, the check for testValue is Nil and I am building up the dictionary again but after one run it should be persistent on the Phone, right?
Am I doing something wrong somewhere in between? I have the feeling that I yet didn't really understand how to load and save settings persistent for a certain application on the iPhone.
Is there anything I have to do additionally to this? Integrating a settings.bundle in XCode or saving the dictionary manually to the Documents folder?
Can someone help me out here? Thanks a lot!
registerDefaults doesn't actually write anything to disk. It just creates a 'defaults defaults' dictionary in memory. So everytime you restart the app, testValue should be nil.
If you want to set persistent values, use setObject:forKey:.
I don't know why you aren't getting a valid object back however.