- (void)createButtons
{
NSArray *arr = @[@"读取Plist文件",@"写入Plist文件"];
for (int i=0; i<2; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom ];
btn.frame = CGRectMake(40, 100+i*200, 300, 40);
btn.titleLabel.font = [UIFont systemFontOfSize:26];
[btn setTitle:arr[i] forState:UIControlStateNormal];
btn.tag = 100+i;
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
self.view.backgroundColor = [UIColor lightGrayColor];
}
//1.2定义按钮点击事件处理方法
- (void)btnClick:(UIButton *)btn
{
//2读取Plist文件
if (btn.tag == 100) {
//2.1.取出PLIST文件路径
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"MyList" ofType:@"plist"];
//2.2读取文件内容创建字典
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:plistPath];
//2.3取到字典中数据
NSString *userName = [dict objectForKey:@"UserName"];
NSString *passWord = [dict objectForKey:@"Password"];
NSString *nickName = [dict objectForKey:@"NickName"];
//2.3.1遍历子成员数组获取字典对象
for (NSDictionary *dict in array) {
NSLog(@"dict = %@", dict);
}
NSLog(@"userName:%@",userName);
NSLog(@"passWord:%@",passWord);
NSLog(@"nickName:%@",nickName);
}else{
//3.创建写入Plist文件数据
//plist文件中的根节点只能是数组或字典,plist文件中存放的数据只能
是NSDATA,NSDATE,NSString,NSNumber,Bool,NSArray,NSDictionary
//3.1构建写入plist中的字典或者数组
NSArray *array = @[@"first",@"second",@"third"];
NSDictionary *dict = [NSDictionary
dictionaryWithObjectsAndKeys:@"one",@"1",@"two",@"2",array,@"array", nil];
//3.2组合字典文件路径
NSString *plistPath = [[[NSBundle mainBundle]bundlePath] stringByAppendingString:@"/mydata.plist"];
//3.3写入plist文件
BOOL res = [dict writeToFile:plistPath atomically:YES];
if (res) {
NSLog(@"写入成功");
}else{
NSLog(@"写入失败");
}
}
}
//*****************************NSUserDefault文件解析*****************************
- (void)btnClick:(UIButton *)btn
{
//应用程序的Defaults System
//1.创建(单例方法,取到应用程序中的默认的Defaults System)
NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
if (btn.tag == 101) {
//1.2设置df
[df setObject:@"AAA" forKey:@"KEY_AAA"];
[df setObject:@"BBB" forKey:@"KEY_BBB"];
//1.3同步数据,只有执行了这行代码,往df中写入数据,才会真正的执行
BOOL res = [df synchronize];
if (res) {
NSLog(@"同步写入成功");
}else{
NSLog(@"同步写入失败");
}
}else{
//2读取
NSString *aaa = [df objectForKey:@"KEY_AAA"];
NSLog(@"%@",aaa);
}
}