iOS.UI_NSUserDefaults的使用

來源:互聯網
上載者:User

標籤: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,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  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的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.