Search code examples
objective-ciosplistnsbundle

access to plist in app bundle returns null


I'm using a piece of code I've used before with success to load a plist into an array:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"species_names" ofType:@"plist"];
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];

The initWithContentsOf File is failing (array is null, suggesting it can't find the plist in the app bundle).

Under the iPhone simulator I've checked that the path created by the first line points to the app file (it does), and used the Finder context menu "Show package contants" to prove to myself that "species_name.plist" is actually in the bundle--with a length that suggests it contains stuff, so it should work (and has in other iOS apps I've written). Suggestions most welcome...

[env Xcode 4.2 beta, iOS 4.3.2].


Solution

  • You should use initWithContentsOfFile: method of NSDictionary instance, not NSArray. Here is sample:

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"species_names" ofType:@"plist"];
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:filePath];
    NSArray *array = [NSArray arrayWithArray:[dict objectForKey:@"Root"]];
    

    Or this:

    NSString *errorDesc = nil;
    NSPropertyListFormat format;
    NSString    *path = [[NSBundle mainBundle] pathForResource:@"startups" ofType:@"plist"];
    NSData      *plistXML = [[NSFileManager defaultManager] contentsAtPath:path];
    NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization                     
                                              propertyListFromData:plistXML
    mutabilityOption:NSPropertyListMutableContainersAndLeaves
                                              format:&format
                                              errorDescription:&errorDesc];
    NSArray *array = [NSArray arrayWithArray:[temp objectForKey:@"Root"]];
    


    EDIT

    You can use initWithContentsOfFile: method of NSArray with file created with writeToFile:atomically: method of NSArray. Plist created with writeToFile:atomically: has this stucture:

    <plist version="1.0">
    <array>
        ...Content...
    </array>
    </plist>
    

    And Plist created in XCode has this stucture:

    <plist version="1.0">
    <dict>
        ...Content...
    </dict>
    </plist>
    

    Thats why initWithContentsOfFile: method of NSArray dosnt work.