2011-07-12 15:21:55| 分類: iphone_dev_note|舉報|字號 訂閱xcode
用戶輕量級的數據持久化,主要用於保存用戶程序的配置等信息,以便下次啓動程序後能恢復上次的設置。iphone
該數據其實是以「鍵值對」形式保存的(相似於NSDictionary),所以咱們須要經過key來讀取或者保存數據(value)。ide
具體使用以下:函數
一、獲取一個NSUserDefaults引用:spa
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];code
二、保存數據orm
[userDefaults setInteger:1 forKey:@"segment"];blog
[userDefaults synchronize];ip
三、讀取數據ci
int i = [userDefaults integerForKey:@"segment"];
四、其餘數據的存取
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];
五、應用實例
-(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中,特別要注意的是蘋果官方對於nsuserdefaults的描述,簡單來講,當你按下home鍵後,nsuserdefaults是保存了的,可是當你在xcode中按下stop中止應用的運行時,nsuserdefaults是沒有保存的,
因此推薦使用[[nsuserdefaults standardUserDefaults] synchronize]來強制保存nsuserdefaults.