用户轻量级的数据持久化,主要用于保存用户程序的配置等信息,以便下次启动程序后能恢复上次的设置。
该数据实际上是以“键值对”形式保存的(类似于NSDictionary),因此我们需要通过key来读取或者保存数据(value)。
具体使用如下:
1、获取一个NSUserDefaults引用:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
2、保存数据
[userDefaults setInteger:1 forKey:@"segment"];
[userDefaults synchronize];
3、读取数据
int i = [userDefaults integerForKey:@"segment"];
4、其他数据的存取
The NSUserDefaults
class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData
,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
.
保存数据:
NSData *objColor = [NSKeyedArchiver archivedDataWithRootObject:[UIColor redColor]];
[[NSUserDefaults standardUserDefaults]setObject bjColor forKey:@”myColor”];
读取数据:
NSData *objColor = [[NSUserDefaults standardUserDefaults]objectForKey:@”myColor”];
UIColor *myColor = [NSKeyedUnarchiver unarchiveObjectWithData bjColor];
5、应用实例
-(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]; //调用synchronize函数将立即更新这些默认值。
[str release];
}
5. 需要检测NSUserDefaults?是否有对应的用户名,如果没有,就加载一个模式视图控制器。
问题是运行之后即使用户名是nil,检测的结果还是存在。
//Check if the login data existsNSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; if ([defaults objectForKey:@"username"] != nil) { //Load Login View if no username is found NSLog(@"No username found"); LoginViewController *loginView = [[LoginViewController alloc] init]; [self presentViewController:loginView animated:YES completion:nil]; } else { NSString *savedUsername = [defaults stringForKey:@"username"]; NSLog(@"Username found: %@", savedUsername); }
在nsuserdefaults中,特别要注意的是苹果官方对于nsuserdefaults的描述,简单来说,当你按下home键后,nsuserdefaults是保存了的
但在xcode中按下stop停止应用的运行时,nsuserdefaults是没有保存的,
所以推荐使用[[nsuserdefaults standardUserDefaults] synchronize]来强制保存nsuserdefaults.