技术 NSUserDefaults的使用
Posted gorpelns
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了技术 NSUserDefaults的使用相关的知识,希望对你有一定的参考价值。
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:1 forKey:@"segment"];
[userDefaults synchronize];
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: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的使用的主要内容,如果未能解决你的问题,请参考以下文章
使用常量 NSString 作为 NSUserDefaults 的键
使用 NSUserDefaults 保存和检索 UILabel 值