Ios development-application settings and user default settings [2. Read application settings], and ios default settings

Source: Internet
Author: User
Tags notification center

Ios development-application settings and user default settings [2. Read application settings], and ios default settings

In the previous section, we explored the basic functions of application system settings and learned about the basic development of bundle packages and plist files. Users can use the Setting application to declare their preference settings. How can we call the parameters set by users? in the previous section, we only created the Setting. bundle. On this basis,In this section, we will continue to discuss how to read the settings in the application and synchronize the data between the application and the settings.

We will achieve the following results through this section:

Figure 1 app page]

[Development Environment: Xcode: 7.2 iOS Simulator: iphone6S plus By: ah Left]

 

1. Get user settings

1. Introduction to the NSUserDefaults class

The NSUserDefaults class must be called to access user settings. The NSUserDefaults class is a singleton class, and the class method standardUserDefaults must be called to obtain the pointer pointing to the standard user's default settings:

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
Defaults can be called into methods like the NSDictionary class, such as "objectForKey:", which will return an Object-C object, such as NSString, NSDate, NSNumber. If you need to obtain integer, floating point, etc., you can use "intForKey:", "floatForKey", "boolForKey" and other methods.
2. Key value

In the previous section, the preference setting field in the plist attribute list, each entry has a specific key, for example, Item1 corresponds to "officer", the slider Item6 corresponds to "SliderValue", these keys are used as calls The ID of the item.

Therefore, we can first put these keys in the header file "settingHead.h" created by ourselves to facilitate the call. The contents are as follows:

#ifndef settingHead_h
#define settingHead_h

#define Officer @ "officer"
#define AuthorizationCode @ "authorizationCode"
#define Rank @ "rank"
#define IsWarp @ "IsWarp"
#define SliderValue @ "SliderValue"
#define moreFactor @ "MoresliderValue"

#endif / * settingHead_h * /
3. Associate related controls

Next, we use Main.storyboard to create 14 labels, a switch, and a slider, and modify the 8 labels on the left to Office, code, etc. as follows:



[Figure 2 Main.storyboard setting interface]

Confirm that the view is associated with ViewController, and then open the auxiliary editor (or press option + command + return on the Main.storyboard interface), hold down the control key and drag from the Main.storyboard icon to ViewController.h, respectively, to the right 6 A label, slider, and switch are added to the interface of ViewController.h. The code is as follows:

#import <UIKit / UIKit.h>

@interface ViewController: UIViewController

// 5 label interfaces
@property (weak, nonatomic) IBOutlet UILabel * label1;
@property (weak, nonatomic) IBOutlet UILabel * label2;
@property (weak, nonatomic) IBOutlet UILabel * label3;
@property (weak, nonatomic) IBOutlet UILabel * label4;
@property (weak, nonatomic) IBOutlet UILabel * label5;

// Slider, switch interface
@property (weak, nonatomic) IBOutlet UISwitch * enginesSwitch;
@property (weak, nonatomic) IBOutlet UISlider * WarpSlider;

// Interface method of slider and switch (modify user default settings)
-(IBAction) enginesSwitchBtn: (UISwitch *) sender;
-(IBAction) WarpSliderBtn: (UISlider *) sender;

@end
In ViewController.m, type: #import "settingHead.h" add the header file of the key collection, and then add a method to update the app interface data:-(void) refreshValue, the code is as follows:

 1 #import "ViewController.h"
 2 #import "settingHead.h"
 3
 4 @implementation ViewController
 5
 6-(void) viewDidLoad {
 7 [super viewDidLoad];
 8 self.view.backgroundColor = [UIColor orangeColor];
 9 [self refreshValue];
10}
11
12-(void) refreshValue
13 {
14 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
15 self.label1.text = [defaults objectForKey: Officer];
16 self.label2.text = [defaults objectForKey: AuthorizationCode];
17 self.label3.text = [defaults objectForKey: Rank];
18 self.label4.text = [defaults boolForKey: IsWarp]? @ "Enable": @ "Disable";
19 self.label5.text = [[defaults objectForKey: SliderValue] stringValue];
20
21 self.enginesSwitch.on = [defaults boolForKey: IsWarp];
22 self.WarpSlider.value = [defaults floatForKey: SliderValue];
twenty three }
 

In the refreshValue method above, first obtain the standard user default settings by calling the NSUserDefaults class, and then call the objectForKey method to access the content of the corresponding key value,

It should be noted that label1 to label5, except label4, are returned in the form of NSString objects. The default key in label4 calls the method of IsWarp to return the bool value. Therefore, after we get the result, we will judge and assign the text to label4;

Since label5 is the value of the slider, it is returned in the form of NSNumber, so you need to call the stringValue method of the object to obtain the string representation of the value it stores.

 

Second, modify the user default settings in the application

The method called by the user to modify the default settings in the application is: "setObject forKey:". In ViewController.m, the following code needs to be added to the associated switch slider methods WarpSliderBtn, enginesSwitchBtn:

 1-(IBAction) WarpSliderBtn: (UISlider *) sender {
 2 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
 3 [defaults setFloat: self.WarpSlider.value forKey: SliderValue];
 4 [defaults synchronize];
 5}
 6-(IBAction) enginesSwitchBtn: (UISwitch *) sender {
 7 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
 8 [defaults setBool: self.enginesSwitch.on forKey: IsWarp];
 9 [defaults synchronize];
10}
Running, we can see the following interface:

【image 3  】

We can see that even if we set the default value for Multi Value and IsWarp, it will still not be displayed in our application. This is because: our application does not know the preference settings of the application saved in the setting bundle at all, even if We set the corresponding value in the settings, and then run it again to see the value displayed on the application, but when we delete the application and run it again, it still displays an empty value, and we cannot see the default value.

We can do the following: if we try to find the unset key / value, but the key will have at least a default value, we can use registerDefaults: method, in order to make the settings effective in the entire application, it is best to start the application Call it

Therefore, click the AppDelegate.m file, add the "settingHead.h" header file, and then type the following code in didFinishLaunchingWithOptions:

1-(BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions: (NSDictionary *) launchOptions {
2 // Override point for customization after application launch.
3
4 NSDictionary * dict = @ {@ "warp": @ YES,
5 @ "warpFactor": @ 5,
6};
7 [[NSUserDefaults standardUserDefaults] registerDefaults: dict];
8 return YES;
9 }
Press command + shift + H, long press the app we created on the ios simulator homepage, delete it, and then press command + R to run again. We can see the default values we just set through the registerDefaults: method.

 

3. Synchronize system settings and application data

Now we can try to modify the system setting values by adjusting the application, but the strange thing is: when we modify the system settings, and then open the app, the data on the app has not changed, when we modify the slider and switch on the app, then check The system settings have not changed.

   This is also a feature of the ios system: when the application returns to the main screen when it is running, it does not exit the application, but it is suspended by the operating system in the background, so that it can be quickly started at any time, because the user is switching applications , Waking up an application saves a lot of time than restarting an application, which makes the switching of applications under the ios system more efficient and faster. This is also the basic knowledge of background applications.

So in this example, how should we update the data synchronously? In fact, as long as we add a function when we wake up: reload the synchronized user preferences and redisplay their contents.

Next we need to apply a lightweight mechanism for "notification" to communicate between objects. The notification center is a singleton object whose purpose is to transmit notifications between objects. "Notifications" are usually instructions sent when certain events occur. The UIApplicaton class sends a large number of notifications (you can find these more detailed content in the Xcode document reader at the bottom of the UIApplicaton page).

When the application returns to the foreground, refresh the content it displays, so we need to call the notification named "UIApplicationWillEnterForegroundNotification", write viewWillAppear: method, we will subscribe to the notification, and tell the notification center to call the method when the notification appears , This method can be named as: "applicationwillenterforegound",

Click ViewController.m and add the following code:

1-(void) applicationwillenterforegound: (NSNotification *) notification
2 {
3 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
4 // Synchronize the application settings with the data on the control
5 [defaults synchronize];
6 [self refreshValue];
7}
Among them, we can see that defaults calls the synchronize method, which forces the user to save the unsaved changes by default, and then reloads all unmodified preferences from storage. In fact, this is to force it to re-read the saved preference settings, so as to obtain the changes made in the settings application, and then call the refreshValue: method to update the displayed content.

Now, we need to implement the viewWillAppear: method in ViewController.m so that the controller subscribes to the "UIApplicationWillEnterForegroundNotification" notification that we follow. as follows:

1-(void) viewWillAppear: (BOOL) animated
2 {
3 [super viewWillAppear: animated];
4 // Register observer
5 UIApplication * app = [UIApplication sharedApplication];
6 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector (applicationwillenterforegound :) name: UIApplicationWillEnterForegroundNotification object: app];
7}
In the addObserver: selector: name: object: method,

The observer passes self, which is our controller itself;

The selector calls the selector method written by us, which is used to tell the notification center to call the method when the notification is issued;

name is the name of the notification we want to receive, generally these more detailed contents can be found in the Xcode document reader;

The last parameter app is the source object we are interested in getting the notification. If it is changed to nil, it means that as long as there is a method to issue the "UIApplicationWillEnterForegroundNotification" notification, we will be notified.

In this way, we are finished, back to the app front desk to reload the content development.

 

So when the user operates the control in the application, how can the content be synchronized to the default settings of the system? It's very simple, just add a line "[defaults synchronize]" to the controls, switches and sliders we set.

-(IBAction) WarpSliderBtn: (UISlider *) sender {
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    [defaults setFloat: self.WarpSlider.value forKey: SliderValue];
    [defaults synchronize];
}
-(IBAction) enginesSwitchBtn: (UISwitch *) sender {
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool: self.enginesSwitch.on forKey: IsWarp];
    [defaults synchronize];
}
[Note: Calling the synchronize: method will be very expensive, because you want to compare all user preferences in the application and system settings, so you should minimize the calls to synchronize, but like our project, in response to each user Calling it once during operation will not cause any significant performance problems. 】

Of course, in order to make the system's working process more clear, we can cancel the registration in viewDidDisappear when the notification system does not need to receive the notification, so we can add the code as follows
1-(void) viewDidDisappear: (BOOL) animated
2 {
3 [super viewDidDisappear: animated];
4 / *
5 Logout monitoring can also use the removeObserver: self name: object: method to cancel a subscription to a specific notification, but the following is more convenient: directly inform the method of ensuring that the notification center completely forgets our observer, regardless of how many types it is registered to receive Notice.
6 * /
7 [[NSNotificationCenter defaultCenter] removeObserver: self];
8 }
Press "command + R" to run. Edit in the application space [refer to Figure 1] and system settings, and check the synchronization effect when switching.

       After doing the above work, we can already understand the basic concepts of setting the application and user default mechanism, how to add bundles, how to build a structured view of the application's preference settings, read and write preferences and modify the settings through NSUserDedeults, and Developed related projects.

 

By: Ah left ~~

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.