在做iOS開發時,經常用到到plist文件, 那plist文件是什么呢? 它全名是:PRoperty List,屬性列表文件,它是一種用來存儲串行化后的對象的文件。屬性列表文件的擴展名為.plist ,因此通常被稱為 plist文件。文件是xml格式的。Plist文件通常用于儲存用戶設置,也可以用于存儲捆綁的信息我們創建一個項目來學習plist文件的讀寫。1、創建項目Plistdemo項目創建之后可以找到項目對應的plist文件,打開如下圖所示:在編輯器中顯示類似與表格的形式,可以在plist上右鍵,用源碼方式打開,就能看到plist文件的xml格式了。2、創建plist文件。按command +N快捷鍵創建,或者File —> New —> New File,選擇Mac OS X下的Property List創建plist文件名為plistdemo。打開plistdemo文件,在空白出右鍵,右鍵選擇Add row 添加數據,添加成功一條數據后,在這條數據上右鍵看到 value Type選擇Dictionary。點加號添加這個Dictionary下的數據添加完key之后在后面添加Value的值,添加手機號和年齡創建完成之后用source code查看到plist文件是這樣的:[cpp] view plaincopy <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>jack</key> <dict> <key>phone_num</key> <string>13801111111</string> <key>age</key> <string>22</string> </dict> <key>tom</key> <dict> <key>phone_num</key> <string>13901111111</string> <key>age</key> <string>36</string> </dict> </dict> </plist> 3、讀取plist文件的數據現在文件創建成功了,如何讀取呢,實現代碼如下:[cpp] view plaincopy - (void)viewDidLoad { [super viewDidLoad]; //讀取plist NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistdemo" ofType:@"plist"]; NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath]; NSLog(@"%@", data);//直接打印數據。 } 打印出來的結果:[cpp] view plaincopy PlistDemo[6822:f803] { jack = { age = 22; "phone_num" = 13801111111; }; tom = { age = 36; "phone_num" = 13901111111; }; } 這樣就把數據讀取出來了。4、創建和寫入plist文件在開發過程中,有時候需要把程序的一些配置保存下來,或者游戲數據等等。 這時候需要寫入Plist數據。寫入的plist文件會生成在對應程序的沙盒目錄里。接著上面讀取plist數據的代碼,加入了寫入數據的代碼,[cpp] view plaincopy <strong>- (void)viewDidLoad { [super viewDidLoad]; //讀取plist NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistdemo" ofType:@"plist"]; NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath]; NSLog(@"%@", data); //添加一項內容 [data setObject:@"add some content" forKey:@"c_key"]; //獲取應用程序沙盒的Documents目錄 NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString *plistPath1 = [paths objectAtIndex:0]; //得到完整的文件名 NSString *filename=[plistPath1 stringByAppendingPathComponent:@"test.plist"]; //輸入寫入 [data writeToFile:filename atomically:YES]; //那怎么證明我的數據寫入了呢?讀出來看看 NSMutableDictionary *data1 = [[NSMutableDictionary alloc] initWithContentsOfFile:filename]; NSLog(@"%@", data1); // Do any additional setup after loading the view, typically from a nib. } </strong> 在獲取到自己手工創建的plistdemo.plist數據后,在這些數據后面加了一項內容,證明輸入寫入了。怎么證明添加的內容寫入了呢?下面是打印結果:代碼地址:https://github.com/schelling/YcDemo/tree/master/PlistDemo
新聞熱點
疑難解答