1. 手動創建.plist文件
使用Xcode打開你的項目,使用快捷鍵 command + n 鍵 打開Xcode的模版框,找到Property List
彈出模版框.png
點擊Next 按鈕
創建框.png
圖中紅色的框填入你要創建的plist文件名字
黃色框是plist文件保存的項目Finder的文件夾
綠色框是plist文件在Xcode中左側綠框看到文件夾
注意:名字不可以使用"Info" 否則會跟項目中的Info.plist產生沖突
點擊Create創建
plistList.png
這個就是我們創建的plist文件
注意:只能讀取,代碼不能增刪改,在bundle文件中的plist文件是無法修改的,如果更改需要先從Bundle中移出才可以,把Plist文件從bundle復制到cache目錄下,然后數據就可以改變了
讀取plist文件代碼
//獲取文件路徑
NSString *path = [[NSBundle mainBundle] pathForResource:@"CreatePlistList" ofType:@"plist"];
NSMutableDictionary *userDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:path];
NSString *name = userDictionary[@"XXX"];
NSString *age = userDictionary[@"XXX"];
NSLog(@"name:%@ \n age:%@",name,age);
2. 代碼創建
NSDictionary *userDictionary = @{@"name":@"花花",
@"age":@"18"
};
///獲取本地沙盒Document路徑
NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [documentPath objectAtIndex:0];
///在Document路徑下拼接文件名字
NSString *plistPath = [path stringByAppendingPathComponent:@"CodeCreatePlistList.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
///檢測plistPath路徑是否存在
BOOL isFile = [fileManager fileExistsAtPath:plistPath];
if (isFile) {
///文件存在 刪除之后 寫入
[fileManager removeItemAtPath:plistPath error:nil];
}
///plist文件寫入
BOOL isSuccess = [userDictionary writeToFile:plistPath atomically:YES];
NSLog(@"寫入成功 %@",@(isSuccess));
你可以在拼接文件路徑的時候打印文件路徑,去finder文件查看,找到創建的文件。
代碼demo GitHub鏈接 https://github.com/ShawnWang1/CreatePlistDemo.git