標籤:des style http color io os ar 使用 for
NSUserDefaults的使用
使用者輕量級的資料持久化,主要用於儲存使用者程式的配置等資訊,以便下次啟動程式後能恢複上次的設定。
該資料實際上是以“索引值對”形式儲存的(類似於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];
}
在nsuserdefaults中,特別要注意的是蘋果官方對於nsuserdefaults的描述,簡單來說,當你按下home鍵後,nsuserdefaults是儲存了的,但是當你在xcode中按下stop停止應用的運行時,nsuserdefaults是沒有儲存的,
所以推薦使用[[nsuserdefaults standardUserDefaults] synchronize]來強制儲存nsuserdefaults.
iOS.UI_NSUserDefaults的使用