iOS入門-29本地數據存儲NSUserDefaults

概述

NSUserDefaults一個輕型數據存儲工具類,磁盤存儲的工具類,存儲一些簡單的數據,例如一些app中用到的標示,賬號等(類似於Android中的SharePreferences)。

  • 具體的數據存在沙盒文件中
  • 存儲數據類型必須是可字符串化的

示例

代碼很簡單,設置了存取兩個過程,仔細看log。

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //下面是兩個按鈕,一個點擊之後存儲數據,一個點擊讀取存儲的數據
    UIButton* writeBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    writeBtn.frame = CGRectMake(40, 40, 80, 40);
    
    [writeBtn setTitle:@"write" forState:UIControlStateNormal];
    
    [writeBtn addTarget:self action:@selector(pressWrite) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton* readBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    readBtn.frame = CGRectMake(40, 100, 80, 40);
    
    [readBtn setTitle:@"read" forState:UIControlStateNormal];
    
    [readBtn addTarget:self action:@selector(pressRead) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:writeBtn];
    
    [self.view addSubview:readBtn];
}

//寫入函數
-(void)pressWrite{
    //定義一個用戶數據默認對象
    //NSUserDefaults對象是全局單例,所以使用的standardUserDefaults而不是new
    NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
    
    //存儲的對象最終放置在沙盒的文件中,所以存儲的對象必須能夠字符串化
    //對象
    NSString* nameStr = @"公西華";
    [ud setObject:nameStr forKey:@"name"];
    
    NSNumber* num = [[NSNumber alloc] initWithInt:184];
    [ud setObject:num forKey:@"high"];
    
    //int
    [ud setInteger:30 forKey:@"age"];
    //bool
    [ud setBool:YES forKey:@"married"];
    //Float
    [ud setFloat:134.6 forKey:@"score"];
    
    //數組,裏面的元素也是要能夠字符串化的
    NSArray* array = [NSArray arrayWithObjects:@"100",@"200", nil];
    
    [ud setObject:array forKey:@"array"];
    

}
//讀取函數
-(void)pressRead{
    //將存入的各個參數讀取出來打印一下
    NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
    
    id obj = [ud objectForKey:@"name"];
    
    NSString* nameStr = (NSString*) obj;
    NSLog(@"name=%@",nameStr);
    
    obj = [ud objectForKey:@"high"];
    NSNumber* high = (NSNumber*)obj;
    NSLog(@"high=%@",high);
    
    NSInteger age = [ud integerForKey:@"age"];
    NSLog(@"age=%ld",age);
    
    BOOL married = [ud boolForKey:@"married"];
    NSLog(@"married=%d",married);
    
    float score = [ud floatForKey:@"score"];
    NSLog(@"score=%f",score);
    
    NSArray* array = [ud objectForKey:@"array"];
    NSLog(@"array=%@",array);
}

@end
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章