本节学习内容:
1.NSUserDefaults基本概念
2.NSUserDefaults函数方法
3.NSUserDefaults的使用
setObjectForKey:根据值和Key存储对象
setInteger:存储整型值
setBoool:存储布尔值
objectForKey:根据Key获取对象值
integerForKey:获取整形值根据Key
boolForKey:获取布乐值根据Key
【ViewController.m】
-(void)viewDidLoad{
super viewDidLoad];
UIbutton* btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame=CGRectMake(100,100,80,40);
[btn.frame=CGRectMake(100,100,80,40);
[btn setTitle:@"写入文件"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:@"读出文件"forState:UIControlStateNormal];
[btnRead addTarget:self action:@selector(pressRead)forControlEvents:UIcontrolEventTouchUpInside];
[self.view addSubview:btnRead];
}
//按下写入数据按钮
-(void)pressWrite{
//定义一个用户默认数据对象,不需求alloc创建,用户默认数据对象单例模式,standardUserDefaults:获取全局唯 一的实例对象
NSUserDfaults* ud=[NSUserDefaults standardUserDefaults];
//存储字符吕对象,可以将对象存储到内部文件中,参数1:要存储的对象(id),参数2:对象的名字(字符串 NSString)
[ud setObject:@"Michael" forKey:@"NAME"];
NSNumber* num=[NSNumber numberWithInt:100];
//存储数据对象。只能存储能够文件 化的对象
[ud setObject:num forKey:@"NUM"];
//不能存储动态创建的对象,不能存储不能文件化的对象
//[ud setObject:self.view forKey:@"VIEW"];
//存储整形数据
[ud setInteger:123 forKey:@"INT"];
//存储布尔型
[ud setBool:YES forKey:@"BOOL"];
//存储浮点型
[ud setFloat:1.555 forKey:@"FLOAT"];
//创建一个可文件化的数组
NSArray* array=【NSArray arrayWithObjects:@"11",@"22",@""33,nil】;
[ud setObject:array forKey:@""ARRAY];
//删除写入元素
[ud removeObjectForKey:@"ARRAY"];
}
-(void)pressRead{
NSUserDefaultes* ud=[NSUserDefaults standardUserDefalults];
id object=[ud objectForKey:@"NAME"];
NSString* name=(NSString*)object;
NSLog(@"name=%@",name);
//输出结果:name=Michael
object=[ud objectForKey:@"NUM"]
NSNumber* num=(NSNumber*)object;
NSLog(@"num=%@,num");
//输出结果:num=100
NSInteger iV=[ud integerForKey:@"INT"];
NSLog(@"iV=%ld",iV);
//输出结果:iV=123
BOOL bv=[ud boolForKey:@"BOOL"];
float fv=[ud floatForKey:@"FLOAT"];
NSLog(@"bv=%d",bv);
//输出结果 bv=1
NSLog(@"fv=%f",fv);
//输出结果 fv=1.555000
NSArray* array=[ud objectForKey:@"ARRAY"];
NSLog(@"array=%@",array);
//输出结果: arry=nil
}
网友评论