想寫這篇博客其實在一兩個月前開發遇見的時候就想把這個問題寫成博客的,奈何自己一直懶外加一直沒有時間,就把這個事情給耽擱了,好在當時知道下自己一定要把這個問題給描述出來,免得以后其他人遇到這個問題會糾結很久(其實就是我啦,基礎知識不過關),所以當時就把這個過程給記錄下來了
給這篇博客命名的時候,是不知道該怎么取名字的(語文不好),因為實在難以描述清楚,於是把它歸為了 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目錄,接下來你就可以對它進行寫入操作咯!