How to ship applications with some preferences set to a set value - iphone

I have one preference in my application that I want my app to be "shipped" with, how do I do this?
Thanks in advance.

Create an NSDictionary then use
[myDict setObject:#"defaultvalue" forKey:#"mykey"];
for each of your default values. Then use
[[NSUserDefaults standardUserDefaults] registerDefaults:myDict];
It is safe to always do this on startup as it won't overwrite settings. When you go to read the value for your settings via
[[NSUserDefaults standardUserDefaults] objectForKey:#"mykey"];
you will get your default value, or the value that you subsequently set.

Store this preference in your app bundle as part of some set of defaults. When your app launches for the first time (an no saved preferences exist) save this value to NSUserDefaults, the documents directory, or where ever you store your app's preferences.

If there is nothing set in the defaults for a given key, set something. You can do this check whenever your app loads, at any time after the first run, you'll always have an object for your #"MySpecialPref" key.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults objectForKey:#"MySpecialPref"]) {
[defaults setBool:YES forKey:#"MySpecialPref"];
}

You could also ship it with a default SQLite database that contains custom values, and use them in your app

Related

Consistent NSUserDefaults saving

So in my app, I was saving some integer keys in NSUserDefaults,like around a minimum of 20.
Something like this but many:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger:1 forKey:#"game1"];
[prefs setInteger:1 forKey:#"game2"];
[prefs setInteger:1 forKey:#"game3"];
So I was just wondering, should I call:
[[NSUserDefaults standardUserDefaults] synchronize];
Everytime I save?
Because sometimes I'm experiencing an inconsistency of the integer I'm saving and have been loading either with stopping, running the app in xCode or from the Home Button.
I have read a couple of articles on a site that stated:
In iOS4, your User Defaults may not get saved when pressing the home button. Manually calling [[NSUserDefaults standardUserDefaults] synchronize] in applicationDidEnterBackground: should ensure that your User Defaults is saved correctly.
Is this true and the same in iOS5? Or are there more accurate ways, shorter ways of saving integers. Thanks for the help.
Apple's documentation says this:
"Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes."
So, depending on the urgency of the data you are settings, you may of may not need to call synchronize. Full documentation is here.
No you don't need to, when you call setInteger:forKey: on prefs, it automatically gets saved.

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

Cannot set NSUserDefault ToggleSwitch Value

I have a form within my IPad app that allows the user to configure the application settings (they can also change these settings from the IPad settings app). I have the following code:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:externalAddress forKey:#"firstString_preference"];
[defaults setValue:internalAddress forKey:#"secondString_perference"];
[defaults setValue:isConnectedToDemoString forKey:#"firstToggle_preference"];
[defaults setValue:isConnectedToInternal forKey:#"secondToggle_preference"];
[defaults synchronize];
The firstString_preference and secondString_perference are Textfields in the settings bundle and they save to the settings without issue. My problem is the firstToggle_preference and secondToggle_preference are toggle switches in the settings bundle and I cannot seem to set these at all. They always seem to be set to no.
Does anyone know what I am doing wrong? Should i be using a different method for setting Toggle Switch default values?
Thanks in advance
What type are isConnectedToDemoString and isConnectedToInternal. Unless those are NSNumbers, you should use setBool:forKey:.
Also, while setValue:forKey: works for storing object types to the user defaults, your code would be clearer if you used the NSUserDefaults-native setObject:forKey: method.

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.