Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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].

like image 410
RonC Avatar asked Aug 05 '11 05:08

RonC


2 Answers

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.

like image 122
VenoMKO Avatar answered Oct 21 '22 04:10

VenoMKO


plist of this type:

enter image description here

OR (basically both are same)

enter image description here

Can be read like this:

NSString *file = [[NSBundle mainBundle] pathForResource:@"appFeatures" ofType:@"plist"];
NSArray *_arrFeats = [NSArray arrayWithContentsOfFile:file];
NSLog(@"%d", _arrFeats.count);

Where appFeatures is name of the plist. (iOS 6.1)

like image 3
Vaibhav Saran Avatar answered Oct 21 '22 04:10

Vaibhav Saran