2011-04-13 152 views
7

.plist文件到底是什麼,我將如何使用它?當我在xcode中查看它時,它似乎會生成某種模板,並顯示一些xml代碼。有沒有辦法通過將內容推入數組中來提取plist文件中的數據?另外,我在哪裏可以查看.plist的來源?Plist:它是什麼以及如何使用它

回答

13

您可以輕鬆地使用下面的代碼獲得的plist的內容到一個數組(我們在這裏開叫「file.plist」的文件,該文件的Xcode項目的一部分):

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"plist"]; 
contentArray = [NSArray arrayWithContentsOfFile:filePath]; 

一個plist中只是相當於一個XML文件一些DTD(數據類型字典)由蘋果設計的DTD可以在這裏看到:

http://www.apple.com/DTDs/PropertyList-1.0.dtd

東西 - 描述了「對象」,而XML文件可以包含數據類型的DTD -among其他。

7

Plist是屬性列表的簡稱。這只是Apple用來存儲數據的文件類型。

您可以在這裏更多的信息:

http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man5/plist.5.html

如果你想的Plist閱讀點擊這裏:

// Get the location of the plist 
// NSBundle represents the main application bundle (.app) so this is a shortcut 
// to avoid hardcoding paths 
// "Data" is the name of the plist 
NSString *path = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"]; 

// NSData is just a buffer with the binary data 
NSData *plistData = [NSData dataWithContentsOfFile:path]; 

// Error object that will be populated if there was a parsing error 
NSString *error; 

// Property list format (see below) 
NSPropertyListFormat format; 

id plist; 

plist = [NSPropertyListSerialization propertyListFromData:plistData 
           mutabilityOption:NSPropertyListImmutable 
           format:&format 
           errorDescription:&error]; 

plist可能是無論在plist中的頂層容器。例如,如果plist是字典,則plist將是NSDictionary。如果plist中是一個數組這將是一個NSArray

這裏的格式枚舉:

enum { 
    NSPropertyListOpenStepFormat = kCFPropertyListOpenStepFormat, 
    NSPropertyListXMLFormat_v1_0 = kCFPropertyListXMLFormat_v1_0, 
    NSPropertyListBinaryFormat_v1_0 = kCFPropertyListBinaryFormat_v1_0 
}; NSPropertyListFormat; 

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/SerializePlist/SerializePlist.html.html

+1

感謝您的代碼。你能夠逐行告訴我你在做什麼嗎?此外,我不知道這些數據類型是什麼(NSBundle,NSData,NSPropertyListFormat,NSPropertyListSerialization)。 – locoboy 2011-04-13 21:09:56

+0

@ cfarm54我更新了一些更多的內嵌評論 – AdamH 2011-04-14 01:03:32

相關問題