iOS 字典和数组写入plist文件存到应用沙盒当中(含读取)

来源:互联网 发布:剑灵召唤师女捏脸数据 编辑:程序博客网 时间:2024/05/15 17:42

写入到应用沙盒

//数据存储是保存在手机里面的    //plist文件存储一般都是存取字典和数组,直接写成plist文件,把它存到应用沙盒当中.    //只有在ios当中才有plist存储,它是ios特有的存储方式.    //获取沙盒根根路径,每一个应用在手机当中都有一个文件夹,这个方法就是获取当前应用在手机里安装的文件.    NSString *homeDir = NSHomeDirectory();    NSLog(@"homeDir = %@",homeDir);    //在某个范围内搜索文件夹的路径.    //directory:获取哪个文件夹    //domainMask:在哪个路径下搜索    //expandTilde:是否展开路径.    //这个方法获取出的结果是一个数组.因为有可以搜索到多个路径.    NSArray *array =  NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);    //在这里,我们指定搜索的是Cache目录,所以结果只有一个,取出Cache目录    NSString *cachePath = array[0];    NSLog(@"%@",cachePath);    //拼接文件路径    NSString *filePathName = [cachePath stringByAppendingPathComponent:@"agePlist.plist"];    //想要把这个字典存储为plist文件.    //直接把字典写入到沙盒当中    //用字典写, plist文件当中保存的是字典.    NSDictionary *dict = @{@"age" : @26,@"name" : @"LayneCheung"};    //获取沙盒路径    //ToFile:要写入的沙盒路径    [dict writeToFile:filePathName atomically:YES];    //用数组写,plist文件当中保存的类型是数组.    NSArray *dataArray = @[@56,@"asdfa"];    //获取沙盒路径    //ToFile:要写入的沙盒路径    [dataArray writeToFile:filePathName atomically:YES];

从沙盒中读取plist文件

//这个方法获取出的结果是一个数组.因为有可以搜索到多个路径.    NSArray *array =  NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);    //在这里,我们指定搜索的是Cache目录,所以结果只有一个,取出Cache目录    NSString *cachePath = array[0];    NSLog(@"%@",cachePath);    //拼接文件路径    NSString *filePathName = [cachePath stringByAppendingPathComponent:@"agePlist.plist"];    //从文件当中读取字典, 保存的plist文件就是一个字典,这里直接填写plist文件所存的路径    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePathName];    NSLog(@"%@",dict);    //如果保存的是一个数组.那就通过数组从文件当中加载.    NSArray *dataArray = [NSArray arrayWithContentsOfFile:filePathName];    NSLog(@"%@",dataArray);
原创粉丝点击