Starting from scratch, I learned ios development (20): Application Settings and User ults (

Source: Internet
Author: User

In the previous study, we learned how to add its Settings for an App, and what types of controls can be added to the Settings items, these controls are managed through a plist. We only need to modify and add the plist to map it to Settings. However, in the previous article, we did not learn the interaction between Settings and apps. In this article, we will learn how to read the values in Settings in an App, how to modify the value in Settings in the App. Now let's start this learning.

1) NSUserDefaults
NSUserDefaults is an object that comes with ios. It mainly serves to set values and assign values to variables in Settings (the control we added. In the previous article, when we created a plist, each Item had a Key, and NSUserDefaults found the object based on the Key, and then obtained the value or assigned a value. This is actually a key-value pair. NSUserDefaults is used in the same way as NSDictionary, so it also has many similar objects such as objectForKey, intForKey, floatForKey, and boolForKey, which are all very simple. In addition, NSUserDefaults is a Singleton mode. That is to say, only one NSUserDefaults object exists in the entire app. This avoids operations on one Item at the same time in two places, in the program, we use the standardUserDefaults method to obtain the NSUserDefaults object:

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

2) read values from Settings
Open BIDMainViewController. h and add the following code:

  kUsernameKey        @"username" kPasswordKey        @"password" kProtocolKey        @"protocol" kWarpDriveKey       @"warp" kWarpFactorKey      @"warpFactor" kFavoriteTeaKey     @"favoriteTea" kFavoriteCandyKey   @"favoriteCandy" kFavoriteGameKey    @"favoriteGame" kFavoriteExcuseKey  @"favoriteExcuse" kFavoriteSinKey     @"favoriteSin" BIDMainViewController : UIViewController <BIDFlipsideViewControllerDelegate>**********- (

The code above defines 10 constant keys to get the values in Settings based on the Key in subsequent code, and then declares 10 IBOutlet, all of which point to the Label, finally, a refreshField method is declared to read the value from Settings and assign it to the Label.

Save the code above and select MainStoryboard in Project navigator. storyboard. Two views are displayed in Layout area, namely Main View and FlipSide View. We select Main View, open Attribute inspector, find Backgrund, and change the background color to white.

In the lower right corner of the Main View, there is an Info button (a circle with an I in the middle), select it, and change its Type to "Info Dark" in Attribute inspector"

In this way, you can easily find the location where it is located.

If you think it is difficult to select a white Info button directly in Main View, you can open Main View Controller Scene and find it conveniently.

Well, next we will drag the control to the Main View, dragging a total of 20 labels, 10 of which are static and only show text, the other 10 need to be associated with the defined IBOutlet to display the values in Settings.

Drag the Label to the Main View.

It doesn't matter what you like. It's mainly about the 10 labels on the right. Their width is the position where the guides appear on the far right to ensure maximum characters.

Okay, the following job is to associate IBOutlet with the Label above the view. A total of 10 labels need to be associated. Select Main View Control in Main View Controller Scene, control-drag to the Label (a row of labels on the right), select the corresponding IBOutlet in the pop-up box

Now, save all the modifications and start encoding below.

Open BIDMainViewController. m and add the following code

- (*defaults ===== [defaults boolForKey:kWarpDriveKey] ?  : ======- (

First, we implemented the refreshFields method, which first declared NSUserDefaults, used to obtain the value in Settings, and then called objextForKey to obtain the value of 10 labels through the Key. There are two special values, the first one is kWarpDriveKey. Since WarpDrive is a Switch, it returns the same bool type. Therefore, it uses the ternary operator to determine whether YES or NO. If YES, "Enabled" is returned ", if NO, "Disabled" is returned ". Another special feature is WarpFactor. Since WarpFactor is a slider and returns an int type, the int type is converted to string output through stringValue.

Then we reload the viewDidAppear method and call the refreshFields method when the view appears.

Find the flipsideViewControllerDidFinish method in BIDMainViewController. m and add the following code

- ()flipsideViewControllerDidFinish:(BIDFlipsideViewController *[self refreshFields];    [self dismissViewControllerAnimated:YES completion:nil];}

There is an info button in the lower-right corner of the Main View. Clicking it will switch to flipsideView. When switching back from flipsideView, the above method will be called and the data in Settings will be refreshed again.

All right, compile and run the program. After the program starts, assign values to each item in ettings in Settings, and then open the ettings program. Then you can see a similar one.

 

3) write the value to Settings
We just read the value from Settings through NSUserDefaults. Now we will learn how to set the value in the program and then write it into Settings.

Open MainStoryboard. storyboard and layout the Flipside View Controller in layout area as follows:

Change the background color of the View to Light Gray color, change the title of the View to "Warp Settings", add two labels, and add a Switch and Slider, the left and right images of Slider are set in Attributs inspector.

Set the minimum value of the slider to 1, the maximum value to 10, and the current value to 5. It is also set in Attributes inspector.

According to the View content, we can see that it is for the switch (WarpDrive) and slider (Warp Factor) in Settings, open BIDFlipsideViewController. h, add the following code

 <UIKit/UIKit.h>- ()flipsideViewControllerDidFinish:(BIDFlipsideViewController * <BIDFlipsideViewControllerDelegate> @property (weak, nonatomic) IBOutlet UISwitch **- (--- (IBAction)done:(

The two IBOutlet naturally point to the Switch and Slider on The View. refreshFields is used to refresh the data on the Flipside. Two ibactions trigger the engineSwitchTapped event when swtich changes, when the slider changes, the warpSliderTouched event is triggered.

The following is the binding. Expand Flipside View Controller Scene.

Select the Flipside View Controller root node, control-drag to switch, and select engineSwitch in the pop-up box.
In the same way, control-drag to slider and select warpFactorSlider.

Then bind the event. This time, select switch in the Flipside View Controller and control-drag to the root node Flipside View Controller in the Flipside View Controller Scene. A box is displayed.

Select enginSwitchTapped, select slider, control-drag, and select warpSliderTouched.

Okay, all the operations on the interface are completed. Start encoding below, open BIDFlipsideViewController. m, and add the following code:

- (    [self refreshFields];}- (*defaults ===-*defaults =-*defaults =

First, call the refreshFields method in viewDidLoad, and then implement refreshFields to read the values in Settings and display them on the interface. Then, two ibactions are implemented. The first is used to save the value of Swtich, the other method saves the value of Slider. Both methods are simple. You can read the code.

OK. Save the compilation and running program, click info button in the lower right corner of the main interface, and switch to flip view.

Flip view shows the value of Warp Drive and Warp Factor in Settings. Then, Let's adjust it, set Warp Engines to ON, and then change the location of Warp Factor, for example

Press Done in the upper left corner and return the main view. The values of Warp Drive and Warp Factor are also changed.

3) set the default value
Now, we can do a lot of things, read the value in Settings in the App, change the value in Settings in the App, and save it back to Settings, but have you found that, when you first run the app, the main view is actually empty and there is nothing. Only when we exit the program and set the value in Settings will we return to the App, in this case, the value in main view is available. In fact, this situation is correct, but we hope that a default value exists. set the default value in bundle, but NSUserDefaults provides us with a method to enable BIDAppDelegate. m, add the following code

  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *    NSDictionary *defaults =

From the code, we can see that NSUserDefaults sets the default value through the registerDefaults method. Its parameter is an NSDictionary and the default value of three objects is set in NSDictionary. Okay. Before re-Compiling and running the program, make sure to delete the deleteheaders in the simulator and then compile and run the program. The effect is as follows:

We can see that the three objects Warp Drive, Warp Factor, and Favorite Sin have default values, which are the same as we expected.

4) Data Synchronization
I believe that the current mobile phone version is at least ios 4 and later. Since ios 4, ios supports multiple tasks (although it is supported on the surface). Users can switch between multiple apps. We can also use this app, but there is a problem: we run the program. The default Interface of the app is as follows:

Press the Home Key to go back to the desktop and enter Settings as Username.

Then exit Settings, and then go to deleettings. You will find that the username you just entered is not displayed.

OK. Now let's solve this problem. First, let's briefly talk about the principle. Here we use a mechanism of ios: Notification. When a background program is activated, it receives a notification: UIApplicationWillEnterForegroundNotification, indicating that the app will be displayed on the foreground. First, we define a method to call this method when notification occurs. Open BIDMainViewController. m and BIDFlipsideViewController. m respectively, and add the following code respectively.

- ()applicationWillEnterForeground:(NSNotification **defaults =

The synchronize method of NSUserDefaults is used to synchronize values in Settings. After the value is synchronized, The refreshFields method is called and displayed in view.

Add the following methods for BIDMainViewController. m and BIDFlipsideViewController. m respectively.

- (*app =

The applicationwillenterforegroundnotification method is used to listen to notifications sent by ios. After listening to the UIApplicationWillEnterForegroundNotification notification, the applicationWillEnterForeground method is called.

We also need to update two methods that have been written, engineSwitchTapped and warpSliderTouched (in BIDFlipsideViewController. m). Modify the following:

-*defaults =[defaults synchronize];}-*defaults =[defaults synchronize];}

Synchronization is added. When the value changes, it is synchronized.

Finally, we need to add a method to release notification, or add the following methods for BIDMainViewController. m and BIDFlipsideViewController. m respectively.

- (

When the view disappears (enters the background or exits the Program), release the notification.

All right, compile and run the app again, press the Home Key to return to the desktop, enter the Settings modification value, and then return to the deleettings. The relative value is changed.

5) Summary
It should be said that this article and the previous article about Settings have been completed, covering a vast majority of Settings operations. This part of content is relatively useful in the process of program design and development, I have gained a lot. At the beginning of the next article, we will focus on how ios implements the data storage function. It is also a very useful content, and almost every app will use it, some storage methods have actually been learned. We will introduce them again in the next chapter. I hope the next article will arrive soon and I will try my best!


AppSettings_all.zip

 

 

 

 

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.