iOS开发遇到的坑之五--解决工程已存在plist表,数据却不能存入的问题

想写这篇博客其实在一两个月前开发遇见的时候就想把这个问题写成博客的,奈何自己一直懒外加一直没有时间,就把这个事情给耽搁了,好在当时知道下自己一定要把这个问题给描述出来,免得以后其他人遇到这个问题会纠结很久(其实就是我啦,基础知识不过关),所以当时就把这个过程给记录下来了

 

给这篇博客命名的时候,是不知道该怎么取名字的(语文不好),因为实在难以描述清楚,于是把它归为了 iOS开发遇到的坑系列文章(如果各位看官认为这确实是我基础的问题,请告诉欧文,我会修改过来的,顺便也学习学习)

大概就是下面这种情况:


  你想要给你的app内置一个plist表,以便app初始化数据的时候直接从里面读取出来进行加载,常见的就是美团客户端上面有一张全国各地的地区plist,因为这个如果每次都从服务器获取的话,因为它比较大,所以下载的时间就比较长,给用户的体验十分不好,所以干脆内置!

  但是问题来了,如果你想给这一张plist表写进数据,恩,那就恭喜入坑,因为你是无论如何写不进去的!(工程里只可读取,不可以写入)

  下面解释一下原因:你在工程目录下直接添加的plist 表和我们通常所说的document目录下的位置是不一样的

    通过代码就可以看出来 : 

1  NSString *filePatch = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"Ads.plist”];

  在文件夹中的显示位置:

 /Users/WayneLiu_Mac/Library/Developer/CoreSimulator/Devices/E6C97A37-A9C1-4F4A-A3EA-EFBB75C1BB43/data/Containers/Data/Application/5E03DC76-7326-4E24-BDBE-F9D5D3072899/Documents/Ads.plist

 

1 NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Ads" ofType:@"plist”]

  在文件夹中的显示位置:

/Users/WayneLiu_Mac/Library/Developer/CoreSimulator/Devices/E6C97A37-A9C1-4F4A-A3EA-EFBB75C1BB43/data/Containers/Bundle/Application/7029EF69-D4A9-45D6-90A7-15794D256688/MZTong.app/Ads.plist,path 

他们在这里已经分路啦!

 

 

存数据只能是document那三个文件夹
必须写到上面的哪个document里面去 要是直接bundle是没有权限的 ,iTunes是可以看到的
 
 
好的,下面说说解决办法吧:
     要想存数据到里面去,你只能在沙盒下的document里进行操作,所以你必须先把你的工程下已经存在的plist表先copy到document里面去
 1 - (void)createEditableCopyOfPlistIfNeeded{
 2     NSFileManager *fileManager = [NSFileManager defaultManager];
 3     NSString *filePatch = AdsPlistPath;
 4     BOOL Exists = [fileManager fileExistsAtPath:filePatch];
 5 //    //删除真机里面的数据
 6 //    BOOL success1 = [fileManager removeItemAtPath:filePatch error:nil];
 7 //    NSLog(@"%hhd",success1);
 8     if(!Exists){
 9 //        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Ads" ofType:@"plist"];
10         NSString *plistPath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"Ads.plist"];
11         NSError *error;
12         BOOL success = [fileManager copyItemAtPath:plistPath toPath:filePatch error:&error];
13         if(!success){
14             NSAssert1(0, @"错误写入文件:'%@'.", [error localizedDescription]);
15         }
16     }
17 
18     NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile:filePatch];
19     
20     
21     if (data.count == 0){
22         NSLog(@"==plist没有数据");
23     }else{
24         self.adsArr = data;
25         NSLog(@"plist 的数据%@", data);//直接打印数据。
26         //        [data removeAllObjects];
27         //        [data writeToFile:filePatch atomically:YES];
28     }
29 }

 

 
然后再使用
1  NSString *filePatch = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"Ads.plist”];

这段代码获取document目录,接下来你就可以对它进行写入操作咯!

 

posted @ 2015-11-12 16:48  Wayne_Liu  阅读(2830)  评论(1编辑  收藏  举报