Use of Nsuserdefaults
User-lightweight data persistence, mainly used to save user program configuration information, so that the next time you start the program can restore the last settings.
This data is actually saved in the form of a "key-value pair" (similar to nsdictionary), so we need to read or save the data (value) via key.
The specific use is as follows:
1. Get a nsuserdefaults reference:
Nsuserdefaults *userdefaults = [Nsuserdefaults standarduserdefaults];
2. Save data
[Userdefaults setinteger:1 forkey:@ "segment"];
[Userdefaults Synchronize];
3. Read data
int i = [userdefaults integerforkey:@ "segment"];
4. Access to other data
The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, booleans, and U Rls. A default object must be a property list, that's, an instance of (or for collections a combination of instances of): ,,,,, NSString NSNumber NSDate NSArray or NSDictionary . If you want to store any other type of object, you should typically archive it to create an instance of NSData .
Save data:
NSData *objcolor = [Nskeyedarchiver archiveddatawithrootobject:[uicolor redcolor];
[[Nsuserdefaults standarduserdefaults]setobject bjcolor forkey:@ "MyColor"];
Read data:
NSData *objcolor = [[Nsuserdefaults standarduserdefaults]objectforkey:@ "MyColor"];
Uicolor *mycolor = [Nskeyedunarchiver unarchiveobjectwithdata bjcolor];
5. Application examples
-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath
{
......
[Cellswitch SetTag:indexPath.row];
[Cellswitch addtarget:self Action: @selector (Switchaction forcontrolevents:uicontroleventvaluechanged];
Retrieving cell switch value
Nsuserdefaults *SWITCHV = [Nsuserdefaults standarduserdefaults];
int i= Indexpath.row;
NSString *str = [[NSString alloc]initwithformat:@ "switch%d", I];
Cellswitch.on = ([Switchv integerforkey:str]==1)? Yes:no;
......
return cell;
}
-(void) Switchaction: (ID) sender
{
int i= [sender tag];
NSString *str = [[NSString alloc]initwithformat:@ "switch%d", I];
Save cell Switch value
Nsuserdefaults *SWITCHV = [Nsuserdefaults standarduserdefaults];
Isonoff = ([sender isOn] = = 1)? 1:0;
[Switchv Setinteger:isonoff forkey:str];
[SWITCHV Synchronize]; Calling the Synchronize function will immediately update these default values.
[STR release];
}
In Nsuserdefaults, it is particularly important to note that Apple's official description of Nsuserdefaults, simply put, when you press the home button, Nsuserdefaults is saved, but when you press stop in Xcode to stop the app's run, Nsuserdefaults is not saved,
It is therefore recommended to use [[Nsuserdefaults standarduserdefaults] synchronize] to force the nsuserdefaults to be saved.
Use of Ios.ui_nsuserdefaults