用户轻量级的数据持久化,主要用于保存用户程序的配置等信息,以便下次启动程序后能恢复上次的设置。
该数据实际上是以“键值对”形式保存的(类似于NSDictionary),因此我们需要通过key来读取或者保存数据(value)。
具体使用如下:
1、获取一个NSUserDefaults引用:
NSUserDefaults *userDefaults = [NSUserDefaultsstandardUserDefaults];
2、保存数据
[userDefaults setInteger:1forKey:@"segment"];
[userDefaults synchronize];
3、读取数据
int i = [userDefaults integerForKey:@"segment"];
4、其他数据的存取
The NSUserDefaults class provides convenience methodsfor accessing common types such as floats, doubles, integers, Booleans, andURLs. A default object must be a property list, that is, an instance of (or forcollections a combination of instances of): NSData,NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type ofobject, you should typically archive it to create an instance of NSData.
保存数据:
NSData *objColor = [NSKeyedArchiverarchivedDataWithRootObject:[UIColor redColor]];
[[NSUserDefaultsstandardUserDefaults]setObject:objColor forKey:@"myColor"];
读取数据:
NSData *objColor = [[NSUserDefaultsstandardUserDefaults]objectForKey:@"myColor"];
UIColor *myColor = [NSKeyedUnarchiver unarchiveObjectWithData:objColor];
5、应用实例
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
......
[cellSwitchsetTag:indexPath.row];
[cellSwitchaddTarget:selfaction:@selector(SwitchAction:) forControlEvents:UIControlEventValueChanged];
//retrieving cellswitch value
NSUserDefaults*switchV = [NSUserDefaults standardUserDefaults];
inti= indexPath.row;
NSString*str = [[NSString alloc]initWithFormat:@"switch%d",i];
cellSwitch.on = ([switchV integerForKey:str]==1)?YES:NO;
......
return cell;
}
-(void)SwitchAction:(id)sender
{
inti= [sender tag];
NSString*str = [[NSString alloc]initWithFormat:@"switch%d",i];
// save cellswitch value
NSUserDefaults*switchV = [NSUserDefaults standardUserDefaults];
isOnOff = ([sender isOn]== 1)?1:0;
[switchV setInteger:isOnOffforKey:str];
[switchV synchronize]; //调用synchronize函数将立即更新这些默认值。
[str release];
}