Can't read from plist

2020-03-31 06:45发布

问题:

I'm trying to do something that I already know how to do - but it isn't working. Looking for ideas to fix this. I think it's something to do with the way Xcode 4.1 creates plist files.

I'm trying to read strings from a plist file, and dump them into an NSArray. This is my code:

NSString *myFile = [[NSBundle mainBundle] 
                                 pathForResource:@"File1"ofType:@"plist"];

myArray = [[NSArray alloc]initWithContentsOfFile: myFile];

I created a plist file in Xcode - an array at the top level and a few strings. myArray is always null. I tried opening the plist in a text editor as I read elsewhere in stackoverflow that Xcode 4 creates a plist with a Dictionary at the top level. I manually edited to make it an array at the top level - no success. Finally, I reverted to the dict at top level and tried to read it into an NSDictionary - also no success.

I have watched tutorial after tutorial and read a number of similar questions on StackOverflow but I just can't get anything read in from a plist file - it is definitely there in the bundle. I have recreated the plist countless times in Xcode. Grateful for any suggestions.

This is what the plist looks like:

<?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>New item</key>
<array>
    <string>Ping</string>
    <string>Pang</string>
    <string>Pong</string>
</array>
</dict>
</plist>

回答1:

The root object of you .plist is a dict, so you need to load it in memory as a NSDictionary.

myDictionary = [[NSDictionary alloc] initWithContentsOfFile: myFile];


回答2:

If you just want the plist loaded, you need to use property list serialization to first load the plist as NSData

[[NSData alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"File1"]]

then serialize it into a dict (or array, depending on what your root item is) using

NSDictionary *aDict = [NSPropertyListSerialization propertyListWithData: options: format: error:]

When you view the plist in Xcode, the top level element is the type to make aDict.

See here for more info: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/SerializePlist/SerializePlist.html

If you want the entire plist loaded as strings, you probably need to do something with an NSString method, something like [NSString stringFromData].