plist是iOS中特有的一种文件形式,将数据写入plist文件的实质就是生成plist文件,那什么样的数据才能生成plist文件呢?答:数组和字典。
1, 将数组写入plist文件(文件储存到cache路径下)
NSArray *words = @[@"a", @"b", @"c", @"d", @"e", @"f", @"g", @"h", @"i", @"j", @"k", @"l", @"m", @"n", @"o", @"p", @"q", @"r", @"s", @"t", @"u", @"v", @"w", @"x", @"y", @"z"];
//获取设备缓存路径
NSString *cachePatch = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
//拼接file路径,最终数据存储到words.plist文件中
NSString *filePath = [cachePatch stringByAppendingPathComponent:@"words.plist"];
//将words数组中数据写入filePath下
[words writeToFile:filePath atomically:YES];
NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory directory, NSSearchPathDomainMask domainMask, BOOL expandTilde )
方法参数说明:
directory: 搜索文件夹
domainMask: 搜索范围 (NSUserDomainMask 代表在用户中查找)
expandTilde: yes 表示路径展开,no 表示路径不展开 用~代替沙盒路径(一般情况用yes)
2,将字典写入plist文件
NSDictionary *personInfo = @{
@"name" : @"amber",
@"age" : @"18",
@"height" : @"165"};
//写入路径
NSString *cachePatch = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [cachePatch stringByAppendingPathComponent:@"personInfo.plist"];
//将路径转换为本地url形式
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
//writeToURL 的好处是,既可以写入本地url也可以写入远程url,苹果推荐使用此方法写入plist文件
[personInfo writeToURL:fileUrl atomically:YES];
3,将元素为字典的数组写入plist文件
NSArray *products = @[
@{@"icon" : @"liantiaobao", @"title" : @"链条包"},
@{@"icon" : @"shoutibao", @"title" : @"手提包"},
@{@"icon" : @"danjianbao", @"title" : @"单肩包"},
@{@"icon" : @"shuangjianbao", @"title" : @"双肩包"},
@{@"icon" : @"xiekuabao", @"title" : @"斜挎包"},
@{@"icon" : @"qianbao", @"title" : @"钱包"}
];
NSString *cachePatch = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [cachePatch stringByAppendingPathComponent:@"products.plist"];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
[products writeToURL:fileUrl atomically:YES];
4,读取plist文件
//获取需要读取数据plist路径
NSString *cachePatch = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [cachePatch stringByAppendingPathComponent:@"products.plist"];
//将plist文件中数据转换成数组形式输出(要预先知道plist中数据类型,否则无法读出)
NSArray *products = [NSArray arrayWithContentsOfFile:filePath];
NSLog(@"%@", products);
参考:小码哥视频资料
网友评论