IOS Programming NSUserDefaults, iosnsuserdefaults

Source: Internet
Author: User

IOS Programming NSUserDefaults, iosnsuserdefaults

IOS Programming NSUserDefaults

When you start an app for the first time, it uses its factory settings. As you use it, a good app learns your preferences. Where are your preferences stored? Inside each app bundle there is a plist that holds the user's preferences. as a developer, you will access this plist using the NSUserDefaults class. the preferences plist for your app can also be edited by the Settings app. to allow this, you create a settings bundle inside your app.

When you first start your app, you use its factory settings. When you use it, a good app will learn your preferences. Where does your preferences exist? In each app bundle, A plist maintains the user preference. As a developer, you can use the NSUserDefaults class. Preferences plist your app can be edited using the setting app. To allow this, you need to create a setting bundle in your app.

1 NSUserDefaults

The set of defaults for a user is a collection of key-value pairs. the key is the name of the default, and the value is some data that represents what the user prefers for that key. you ask the shared user defaults object for the value of that key-not unlike getting an object from a dictionary:

The defaults setting for a user is a key-value pairs container. Key is the name of default, and value represents the data that ELE. Me users like. You ask the shared user ults object to get the value of the key, much like getting the object from a dictionary.

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

NSString * greeting = [defaults objectForKey: @ "FavoriteGreeting"];

If the user expresses a preference, you can set the value for that key:

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

[Defaults setObject: @ "Hello" forKey: @ "FavoriteGreeting"];

This value will automatically be stored to the app's preferences plist. thus, the value must be a plist type: NSArray, NSDictionary, NSString, NSData, NSDate, or NSNumber. if you want to store a non-plist type to the user defaults, you will need to convert it to a plist. often this is accomplished by archiving the object (or objects) into an NSData, which is a plist.

These values are automatically stored in the preference plist of the app. therefore, the value must be plist type: NSArray, NSDictionary, NSString, NSData, NSDate, or NSNumber. if you store a non-plist, You need to convert it to plist. Normally, an object is archived as NSData.

What if you ask for the value of a preference that has not been set by the user? NSUserDefaults will return the factory settings, the "default," if you will. these are not stored on the file system, so you need to tell the shared instance of NSUserDefaults what the factory settings are every time your app launches. and you need to do it early in the launch process-before any of your classes try to read the defaults. typically you will override + initialize on your app delegate:

If you ask whether a preference value has not been set yet? NSUserDefaults will return factory settings, the "default", if you are willing. These are not stored in the file system, so you need to tell the NSUserDefaults shared instance what factory settings should be set every time your app starts. you need to do this before starting the program: Before Your Class View reads ults. Generally, your return weight + initialize is on your app delegate.

+ (Void) initialize

{

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

NSDictionary * factorySettings ={ @ "FavoriteGreeting": @ "Hey! ",

@ "HoursBetweenMothershipConnection: @ 2 };

[Defaults registerDefaults: factorySettings];

}

The class method initialize is called automatically by the Objective-C runtime before the first

Instance of that class is created.

This class method initialize is automatically called in the Objective-C Runtime created by that class.

1.1 Register the factory settings

Register factory Settings

At launch time, the first thing that will happen is the registering of the factory settings. It is considered good style to declare your preference keys as global constants.

At startup, the first thing that will happen is the registration of factory settings. Declaring your preference keys as a global constants is a good way. Open BNRAppDelegate. h and declare two constant global variables:

Extern NSString * const BNRNextItemValuePrefsKey;

Extern NSString * const BNRNextItemNamePrefsKey;

In BNRAppDelegate. m, define those global variables and use them to register the factory defaults in

+ Initialize:

NSString * const BNRNextItemValuePrefsKey = @ "NextItemValue ";

NSString * const BNRNextItemNamePrefsKey = @ "NextItemName ";

 

@ Implementation BNRAppDelegate

+ (Void) initialize

{

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

NSDictionary * factorySettings ={ BNRNextItemValuePrefsKey: @ 75,

BNRNextItemNamePrefsKey: @ "Coffee Cup "};

[Defaults registerDefaults: factorySettings];

}

 

1.2 Read a preference

When you create a new item in BNRItemStore. m, use the default values. Be sure to import BNRAppDelegate. h at the top of BNRItemStore. m so that the compiler knows about BNRNextItemValuePrefsKey.

 

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

Item. valueInDollars = [defaults integerForKey: BNRNextItemValuePrefsKey];

Item. itemName = [defaults objectForKey: BNRNextItemNamePrefsKey];

// Just for fun, list out all the defaults
NSLog (@ "defaults = % @", [defaults dictionaryRepresentation]);

Notice the method integerForKey:. It is there as a convenience. It is equivalent:

Item. valueInDollars = [[defaults objectForKey: BNRNextItemValuePrefsKey] intValue];

There are also convenience methods for setting and getting float, double, BOOL, and NSURL values.

1.3 Change a preference

You cocould create a view controller for editing these preferences. or, you can create a settings bundle for setting these preferences. or, you can just try to guess the user's preferences from their actions. for example, if the user sets the value of an item to $100, that may be a good indication that the next item might also be $100. for this exercise, you will do that.

You can create a view controller to edit these preferences. Or, you can create a settings bundle to set these preferences. Or you can just guess the user's preferences from their actions. For example, if a user sets the value of an item to 100, this is a good indication, and next item may also be 100.

Open BNRDetailViewController. m and edit the viewWillDisappear: method.

 

Int newValue = [self. valueField. text intValue];

// Is it changed?

If (newValue! = Item. valueInDollars ){

// Put it in the item. valueInDollars = newValue;

// Store it as the default value for the next item

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

[Defaults setInteger: newValue forKey: BNRNextItemValuePrefsKey];

Item. valueInDollars = [self. valueField. text intValue];

}

 

Import BNRAppDelegate. h so that the compiler knows about the BNRNextItemValuePrefsKey constant.

Sometimes you will give the user a button that says "Restore factory default", which will remove some defaults from the app's preferences plist.

To remove key-value pairs from your app's preferences plist, NSUserDefaults has a removeObjectForKey: method.

Sometimes you provide a button to the user to re-set the factory default, which will remove all the default values in your app preferences plist. remove all key-value pairs from your app's preferences plist. NSUserDefaults has a removeObjectForKey method.

 

2 Settings Bundle

Now you are going to create a settings bundle so that the NextItemName preference can be changed from "Coffee Cup" to whatever string the user desires.

Now you will create a settings bundle so that NextItemName preference can go from "cofftoffcup" to the data that any user needs.

These days when designers consider settings bundles to be distasteful and most apps do not include a settings bundle. that said, should apps do have settings bundles, so it is a good idea to know how to make them.

These days, many designers think that setting bundles is not good. Many apps do not include setting bundles. That is, many apps have settings bundles, so it is useful to know how to use them.

The bundle is just a directory that holds a plist that describes what controls shoshould appear in this view and what default each control is manipulating.

Bundle only has a plist to indicate what control should appear in this view and a directory for each control default operation.

You will pull the user visible strings (like the label "Default Item Name" in
Figure 26.1) into a strings file that is localized for the user. Those strings files will also be in the settings bundle.

You will put user visible strings into a Strings file for user localization. These Strings files will also be added in settings bundle.

To create a settings bundle inside your app, open Xcode's File menu and choose New → File... Under the iOS Resources pane, choose Settings Bundle

 

Accept the default name. Notice that a directory called Settings. bundle has been created in your project directory. It has a Root. plist file and an en. lprog subdirectory.

1.1 Editing the Root. plist

The Root. plist describes what controls will appear in your app's settings pane. it contains an array of dictionaries; each dictionary represents one view (typically a control) that will appear on the pane. every dictionary must have Type key. here are the acceptable values for Type:

Root. plist indicates what controls will be displayed in your app's setting pane. It contains a column of dictionaries; each dictionary represents a view that will be displayed on pane. Each dictionary must have a Type key. Here are some acceptable values:

PSTextFieldSpecifier

A labeled text field label text

PSToggleSwitchSpecifier

A labeled toggle switch label

PSSliderSpecifier

A slider (not labeled) slide

PSRadioGroupSpecifier

A list of radio buttons; only one can be selected column radio buttons, only one optional

PSMultiValueSpecifier

A table view of possibilities; only one can be selected the possibility of a table view

PSTitleValueSpecifier

A title for formatting

PSGroupSpecifier

A group for formatting

PSChildPaneSpecifier

Lets you move some preferences onto a child pane

Let you move some preferences to child pane.

Notice that you have been laying out a user interface using a plist file. when you create a settings bundle, you are not writing any executable code, and you are not creating any view controllers or other objects that you control. the Settings application will read your application's Root. plist and will construct its own view controllers based on the contents of the plist file.

Note that you have laying out a user interface using a plist file. when you create a setting bundle, You do not write any executable code, nor create any view controller or other objects under your control. Setting application will read the root. plist of your application and build your own view controller Based on plist file.

2.2 Localized Root. strings

Inside your settings bundle is an en. lproj which will hold your English strings. You can delete all the key-value pairs and give the title for your text field:

In your setting bundle is an en. lproj, which will keep your English strings. You can delete all key-value pairs and give the title of your text field.

"NextItemName" = "Default Item Name ";

One final point: when your defaults are changed (by your own app or the Settings app) an NSUserDefaultsDidChangeNotification will get posted to your application. if you want to respond to changes in the Settings app immediately, register as an observer of this notification.

Last point: when your ults changes, NSUserDefaultsDidChangeNotification will be pushed to the application. If you want to promptly respond to the setting app immediately, register as an observer for this notification.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.