// ViewController.m
// plist文件
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
/*
1.根节点只能是数组或者字典
需求:创建一个数组,通过plist文件的形式,将数组保存到Documents文件夹array.plist文件
.plist的不足:
只能保存数组和字典
只能保存Bollean、Data、Date、Number、String这些基本的数据类型
*/
// [self saveArray];
// [self readArray];
[self saveDict];
[self readDict];
}
// 保存数组
-(void)saveArray
{
// 1.创建一个数组
NSArray *array = @[@"1",@"2",@"3"];
// 2.拼接文件路径
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSLog(@"%@",documentsPath);
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"array.plist"];
// 3.写入文件
BOOL success = [array writeToFile:filePath atomically:YES];
NSLog(@"保存数组 success = %@",success?@"YES":@"NO");
/*
如果目标文件不存在,会自动创建.
atomically:线程安全
*/
}
// 读取数组
-(void)readArray
{
// 1.文件路径
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"array.plist"];
// 2.读取
NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
NSLog(@"读取数组 = %@",array);
}
// 保存字典
-(void)saveDict
{
// 1.创建一个数组
NSDictionary *dict = @{@"a":@"1",@"b":@"2",@"c":@"3"};
// 2.拼接文件路径
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSLog(@"%@",documentsPath);
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"dict.plist"];
// 3.写入文件
[dict writeToFile:filePath atomically:YES];
}
// 读取字典
-(void)readDict
{
// 1.文件路径
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"dict.plist"];
// 2.读取
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
NSLog(@"读取字典 = %@",dict);
}
@end
网友评论