N_WIDTH,
BUTTON_HEIGHT)];
[_saveButton setTitle:@"保存数据" forState:UIControlStateNormal];
[_saveButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[_saveButton addTarget:self
action:@selector(saveClick)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_saveButton];
_readButton = [[UIButton alloc] initWithFrame:CGRectMake(CURRENT_SCREEN_WIDTH/2 - BUTTON_WIDTH/2,
_saveButton.frame.origin.y + _saveButton.frame.size.height + 60,
BUTTON_WIDTH,
BUTTON_HEIGHT)];
[_readButton setTitle:@"读取数据" forState:UIControlStateNormal];
[_readButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[_readButton addTarget:self
action:@selector(readClick)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_readButton];
}
- (void)saveClick{
//获取应用程序目录
NSString *home = NSHomeDirectory();
NSLog(@"应用程序目录:%@",home);
//NSUserDomainMask在用户目录下查找
//YES 代表用户目录的~
//NSDocumentDirectory查找Documents文件夹
//建议使用如下方法动态获取
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES) lastObject];
NSLog(@"Documents文件夹路径:%@",doc);
//拼接文件路径
NSString *path = [doc stringByAppendingString:@"/abc.plist"];
//NSArray *array = @[@"ios",@"23"];
//[array writeToFile:path atomically:YES];
//NSDictionary *dict = @{@"name":@"ios",@"age":@"28"};
//[dict writeToFile:path atomically:YES];
/*
plist只能存储系统自带的一些常规的类,也就是有writeToFile方法的对象才可以使用plist保持数据
字符串/字典/数据/NSNumber/NSData ...
*/
//自定义的对象不能保存到plist中
DBPerson *person = [[DBPerson alloc] init];
person.name = @"ios";
}
- (void)readClick{
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES) lastObject];
NSString *path = [doc stringByAppendingString:@"/abc.plist"];
//读取数据
//NSArray *array = [NSArray arrayWithContentsOfFile:path];
//NSLog(@"%@",array);
//NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
//NSLog(@"name = %@",[dict objectForKey:@"name"]);
//NSLog(@"age = %@",[dict objectForKey:@"age"]);
}
@end
五.属性列表 1.属性列表是一种XML格式的文件,拓展名为plist。 2.如果对象是NSString,NSDictionary,NSArray,NSData,NSNumber等类型,就可以使用writeToFile:atomically:方法直接将对象写到属性列表文件中
|