Getting contents of a plist
How can I get the content of this plist?
I am a little confused on the different elements and how to access them.
How does one access these dictionaries, and dictionaries in dictionaries?
What if I want to copy this data first, would it increase performance by a l开发者_如何学Pythonot, rather than always reading from the plist?
How can I get all of this data into my app, by going through the structure levels?
Thank you
The easiest way to read a property list is by using a convenience method on NSDictionary
(Or NSArray
if your root element is an array) like so:
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"FileName"
ofType:@"plist"];
NSDictionary* plist = [NSDictionary dictionaryWithContentsOfFile:filePath];
From there on the plist file is just a normal dictionary. Use objectForKey:
, etc to get to the values. For faster access to deep child nodes you can use valueForKeyPath:
like this for example:
NSString* name = [plist valueForKeyPath:@"mainDictionary.name"];
For more complex operations on plist files you should use NSPropertyListSerialization
that have several class methods for more more fine grained access to reading and writing property list files.
use this :
NSDictionary *dic1 = [[NSDictionary alloc] initWithContentofFile:yourFilePathhere];
// return main dictionary
NSDictionary *dic2 = [dic1 objectForKey:mainDictionary];
You should check out the NSPropertyListSerialization class, which makes parsing plists relatively straightforward.
Here's a bit of sample code: http://iphoneincubator.com/blog/tag/nspropertylistserialization
Swift Code
let filePath:String = NSBundle.mainBundle().pathForResource("infoList_English", ofType: "plist")!
let postDictionary : NSDictionary = NSDictionary(contentsOfFile: filePath)!
print(postDictionary)
精彩评论