PDA

View Full Version : Reading from plist




jschulbach
Jul 22, 2010, 11:21 PM
I'm attempting to load data from a plist file that I've placed in my resources folder in xcode, it's named "FakeData.plist". When I try loading it into a mutable dictionary via the following code the resulting dictionary is nil. I searched the forum and online and have tried a couple different approaches I have seen but am obviously missing something.


NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];

NSString *filePath = [documentsPath stringByAppendingPathComponent:@"FakeData.plist"];
NSMutableDictionary * plistArr = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
if(plistArr){
NSLog(@"value is: %@", [plistArr count]);
}



If I log filePath it shows the full file path so it's getting that correctly, but if I log plistArr I get nil, if I log [plistArr count] it returns 0. Could it be rejecting the plist file? I've logged everything and can't figure out the next step in debugging or why it isn't loading the plist into the dictionary.



dejo
Jul 22, 2010, 11:33 PM
So, you've placed the plist in your Resources but are trying to load it from your Documents directory?

jschulbach
Jul 23, 2010, 12:26 AM
I want to read it from the resources although it does seem to find it in the file in the path search? How do I get the path to the files in resources?

ritsard
Jul 23, 2010, 12:58 AM
you may want to look at NSBundle

jschulbach
Jul 23, 2010, 01:02 PM
Thanks ritsard, that was what I needed. Also for future reference for anyone else with a similar issue, I was trying to load the plist into a dictionary when my plist was set up as an array, switched to an array and it loaded in fine. Here is the final code snippet that worked for me.


NSString *path;

NSBundle *thisBundle = [NSBundle bundleForClass:[self class]];
if (path = [thisBundle pathForResource:@"FakeData" ofType:@"plist"]) {
NSLog(@"value is: %@", path);
NSMutableArray * plistArr = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSLog(@"value is: %@", plistArr);
}