1. 程式人生 > >ios應用資料儲存方式(偏好設定)-轉

ios應用資料儲存方式(偏好設定)-轉

一.簡單介紹 
1.很多ios應用都支援偏好設定,比如儲存使用者名稱,密碼,字型大小等設定,ios提供了一套標準的解決方案來為應用加入偏好設定功能。 
2.每個應用都有個NSUserDefaults例項,通過它來儲存偏好設定。比如,儲存使用者名稱,字型大小,是否自動登入。 
3.儲存位置 
這裡寫圖片描述 
4.儲存形式 
這裡寫圖片描述

 

二.程式碼示例

#import "ViewController.h"

#define CURRENT_SCREEN_WIDTH     [UIScreen mainScreen].bounds.size.width
#define
CURRENT_SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height - 64) #define BUTTON_WIDTH 80 #define BUTTON_HEIGHT 40 @interface ViewController () //儲存資料按鈕 @property(nonatomic,strong) UIButton *saveButton; //讀取資料按鈕 @property(nonatomic,strong) UIButton *readButton; @end @implementation
ViewController - (void)viewDidLoad { [super viewDidLoad]; [self initControl]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } //初始化控制元件 - (void)initControl{ _saveButton = [[UIButton alloc] initWithFrame:CGRectMake(CURRENT_SCREEN_WIDTH/2
- BUTTON_WIDTH/2, CURRENT_SCREEN_HEIGHT/2 - BUTTON_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT)]; [_saveButton setTitle:@"儲存資料" forState:UIControlStateNormal]; [_saveButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; [_saveButton addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:_saveButton]; _readButton = [[UIButton alloc] initWithFrame:CGRectMake(CURRENT_SCREEN_WIDTH/2 - BUTTON_WIDTH/2, _saveButton.frame.origin.y + _saveButton.frame.size.height + 60, BUTTON_WIDTH, BUTTON_HEIGHT)]; [_readButton setTitle:@"讀取資料" forState:UIControlStateNormal]; [_readButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; [_readButton addTarget:self action:@selector(readClick) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:_readButton]; } #pragma mark -按鈕事件 - (void)saveClick{ //獲取NSUserDefaults物件 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; //儲存資料(如果設定資料之後沒有同步,會在將來某一時間點自動將資料儲存到Preferences資料夾下面) [defaults setObject:@"DuBo" forKey:@"name"]; [defaults setInteger:31 forKey:@"age"]; [defaults setDouble:1.76f forKey:@"height"]; //強制讓資料立刻儲存 [defaults synchronize]; } - (void)readClick{ //獲取NSUserDefaults物件 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; //讀取儲存資料 NSString *name = [defaults objectForKey:@"name"]; NSInteger age = [defaults integerForKey:@"age"]; double height = [defaults doubleForKey:@"height"]; //列印資料 NSLog(@"name = %@",name); NSLog(@"age = %d",(int)age); NSLog(@"height = %f",height); } @end

 

三.重要說明 
1.偏好設定是專門用來儲存應用程式的配置資訊的,一般情況不要在偏好設定中儲存其他資料。如果利用系統的偏好設定來儲存資料,預設就是儲存在Preferences資料夾下面的,偏好設定會將所有的資料都儲存到同一個檔案中。 
2.使用偏好設定對資料進行儲存之後,它儲存到系統的時間是不確定的,會在將來某一時間點自動將資料儲存到Preferences資料夾下面,如果需要即刻將資料儲存,可以使用[defaults synchronize]。 
3.所有的資訊都寫在一個檔案中,對比簡單的plist可以儲存和讀取基本資料型別。 
4.獲取NSUserDefaults,儲存 (讀取)資料。