UISB UserDefaults

ViewController.m

 

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame=CGRectMake(100, 100, 80, 40);
    [btn setTitle:@"write" forState:UIControlStateNormal];
    
    [btn addTarget:self action:@selector(presswrite) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btn];
    
    UIButton* btnRead=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnRead.frame=CGRectMake(100, 200, 80, 40);
    [btnRead setTitle:@"read" forState:UIControlStateNormal];
    
    [btnRead addTarget:self action:@selector(pressread) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btnRead];
        
    
}

-(void)presswrite
{
    
    //用户默认数据对象
    //不需要alloc 单例模式
    //standardUserDefaults 获取全局唯一的实例对象
    NSUserDefaults* ud =[NSUserDefaults standardUserDefaults];
    
    //存储字符串对象
    //P1 存储对象
    //P2 对象的名字
    [ud setObject:@"kobe" forKey:@"Name"];
    
    NSNumber* num =[NSNumber numberWithInt:100];
    
    [ud setObject:num forKey:@"Num"];
    
    [ud setInteger:123 forKey:@"INI"];
    [ud setBool:YES forKey:@"Bool"];
    [ud setFloat:1.555 forKey:@"Float"];
    
    // 创建一个可文件化的数据
    NSArray* array = [NSArray arrayWithObjects:@"11",@"22",@"33",nil];
    [ud setObject:array forKey:@"ABBA"];
    
    
  
    
}

-(void)pressread
{
    NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
    
    id object = [ud objectForKey:@"Name"];
    NSString* name =(NSString*) object;
    NSLog(@"name=%@",name);
    
    object = [ud objectForKey:@"Num"];
    NSNumber* num=(NSNumber*) object;
    NSLog(@"num=%@",num);
    
    NSInteger iv = [ud integerForKey:@"INI"];
    NSLog(@"iv=%ld",iv);
    
    
    
    
    
    
}


@end

 

posted @ 2020-10-09 22:33  逆欢  阅读(83)  评论(0编辑  收藏  举报