NSUserDefaults用户默认数据对象

用途

用来存储数据对象,是单例模式,一旦创建就是全局唯一的实例对象。可以在任何位置进行存放和读取里面的数据。

  • 注意:只能存储能够文件化的对象,不能存储动态创建的对象(eg:view)

相关方法

  • +NSUserDefaults standardUserDefaults类方法,创建实例对象
    因为是单例对象,不用alloc来创建
    standardUserDefaults获取全局唯一的实例对象
  • setObject: @"lychee" forKey:@"NAME" 存储对象(字符串,,,)
    P1:要存储的对象 id
    P2:对象的名字key:NSString
  • 要存储整型数据时:
  • setInteger:num forKey:@"NUM"
  • setBool:YES forKey:@"BOOL"
  • setFloat:1.333 forKey:@"FLOAT"
  • 要读取里面存储的数据时:
  • objectForKey:@"name"
  • integerForKey:@"int"
  • boolForKey:@"BOOL"
  • floatForKey:@"float"

具体使用

直接在.m实现文件中:

- (void)viewDidLoad {
    [super viewDidLoad];
    // 在视图中创建两个按钮:存储,读取来验证NSUserDefauls
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(100, 100, 80, 40);
    [btn setTitle:@"写入" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(pressWrite) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn2.frame = CGRectMake(100, 200, 80, 40);
    [btn2 setTitle:@"读出" forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(pressRead) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn2];
    
}
-(void)pressWrite{
    //定义一个用户默认数据对象
    //不需要alloc创建,是单例模式
    //standardUserDefaults获取全局唯一的实例对象
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    
    //存储字符串对象
    //可以将对象存储到内部文件中
    //P1:要存储的对象 id
    //P2:对象的名字key:NSString
    [ud setObject:@"lychee" forKey:@"NAME"];
    
    NSNumber *num = [NSNumber numberWithInt:100];
    //存储数据对象
    //只能存储能够文件化的对象
    //不能存储动态创建的对象(eg:view)
    [ud setObject:num forKey:@"NUM"];
    
    //存储整型数据
    [ud setInteger:123 forKey:@"INT"];
    
    [ud setBool:YES forKey:@"BOOL"];
    
    [ud setFloat:1.5555 forKey:@"FLOAT"];
    
    NSArray *array = [NSArray arrayWithObjects:@"11",@"22",@"33",nil];
    
    [ud setObject:array forKey:@"ARRAY"];
    
    NSLog(@"lalalalaa");
}
-(void)pressRead{
    //读取用户默认对象的内容
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    id object = [ud objectForKey:@"NAME"];
    NSString *name = (NSString*)object;
    NSLog(@"name = %@",name);
    
    NSLog(@"num = %@",[ud objectForKey:@"NUM"]);
    NSLog(@"int = %ld",[ud integerForKey:@"INT"]);
    NSLog(@"bool = %d",[ud boolForKey:@"BOOL"]);
    NSLog(@"float = %f",[ud floatForKey:@"FLOAT"]);
    NSLog(@"array = %@",[ud objectForKey:@"ARRAY"]);
    
}

你可能感兴趣的:(NSUserDefaults用户默认数据对象)