码迷,mamicode.com
首页 > 其他好文 > 详细

NSUserDefaults简介及使用

时间:2014-06-18 17:34:04      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:des   style   class   code   tar   color   

用户轻量级的数据持久化,主要用于保存用户程序的配置等信息,以便下次启动程序后能恢复上次的设置。

该数据实际上是以“键值对”形式保存的(类似于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,NSStringNSNumberNSDateNSArray, 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:objColor forKey:@"myColor"];

读取数据:

 

NSData *objColor = [[NSUserDefaults standardUserDefaults]objectForKey:@"myColor"];

 

UIColor *myColor = [NSKeyedUnarchiver unarchiveObjectWithData:objColor];

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];

 

 

NSUserDefaults简介及使用,布布扣,bubuko.com

NSUserDefaults简介及使用

标签:des   style   class   code   tar   color   

原文地址:http://www.cnblogs.com/ejllen/p/3790897.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!