A detailed description of the preference settings:
Use: Mainly used to store the user's system device information, but sometimes can be used anywhere in the program to store data, as global data to access, such as the view switch needs to log in.
Write Preferences:• Many iOS apps support preferences, such as saving usernames, passwords, font sizes, and more, iOS offers a standard set of solutions to add preferences to your app • Each app has a nsuserdefaults instance, which is a singleton object that accesses preferences, The settings information is in the form of a key-value pair. • For example: Save user name, font size, automatic login
Nsuserdefaults *defaults = [Nsuserdefaults standarduserdefaults];
[Defaults setobject:@ "itcast.cn" forkey:@ "UserName"];
[Defaults setfloat:18.0f forkey:@ "FontSize"];
[Defaults setbool:yes forkey:@ "Autologin"];
preferences for reading:
Read System Preferences
Nsuserdefaults *defaults = [Nsuserdefaults standarduserdefaults];
NSString *username = [Defaults objectforkey:@ "UserName"];
float fontSize = [Defaults floatforkey:@ "FontSize"];
BOOL autologin = [Defaults boolforkey:@ "Autologin"];
Note: When setting the data, Userdefaults does not write immediately, but instead writes the cached data to the local disk according to the timestamp. So when the set method is called, the data may not have been written to the disk, and the application terminates.
The above problems can be enforced by calling the Synchornize synchronous method:
[Defaults synchronize];
Usage of preference settings:
1. set up users Login Information (Preferences)
Nsuserdefaults *userdefaults = [Nsuserdefaults standarduserdefaults];
[Userdefaults setobject:@ "admin" forkey:@ "userName"]; Login user Name
[Userdefaults setobject:[nsdate Date] forkey:@ "logindate"]; Logon Hours
[Userdefaults setinteger:2 forkey:@ "Times"]; Number of Logins
2. Force the set user information to be saved to the preference file in the disk sandbox directory
[Userdefaults Synchronize];
3. Read Preference settings
Nsuserdefaults *userdefaluts = [Nsuserdefaults standarduserdefaults];
NSString *username = [userdefaluts objectforkey:@ "UserName"];
NSDate *date = [userdefaluts objectforkey:@ "Logindate"];
NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
Dateformatter.dateformat = @ "Yyyy-mm-dd HH:mm:ss";
Nsinteger times = [Userdefaluts integerforkey:@ "Times"];
NSLog (@ "Username:%@,date:%@,times:%ld", Username,[dateformatter stringfromdate:date],times);
Demo Result:
£ º33.529-User Preferences [601£ º 20685] username:admin,date:---£º , Times:2
IOS: Understanding and use of preference settings