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

你可能感兴趣的:(iOS)