Problem getting path to .plist using [[NSBundle mainBundle] pathForResource

andrewdotcoza picture andrewdotcoza · Nov 17, 2009 · Viewed 10.2k times · Source

I'm an Objective C noob, and I don't know enough to explain the following problem.

This code works:

NSString *plistPath = @"/Users/andrewf/MyApp/Resources/Plates.plist";
dicPlates = [[NSDictionary alloc] initWithContentsOfFile:plistPath];

My dictionary object is loaded with values as expected.

This code does not work:

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Plates" ofType:@"plist"];
dicPlates = [[NSDictionary alloc] initWithContentsOfFile:plistPath];

plistPath comes back with a value of nil. This is the case irrespective of whether I include inDirectory:@"Resources" in the call or not. All the examples that I have found do not include inDirectory when trying to open a .plist file in the Resources directory.

I have confirmed that the file exists in the correct location and even recreated it to be sure.

This seems like such a simple problem, but I am mystified. Please assist.

Answer

Dave DeLong picture Dave DeLong · Nov 17, 2009

I think you're confused as to where pathForResource: is looking.

This works:

NSString *plistPath = @"/Users/andrewf/MyApp/Resources/Plates.plist";

Notice that this path does not point to your application. It points to your project directory. Your plist is supposed to be at @/Users/andrewf/MyApp/build/Release/MyApp.app/Resources/Plist.plist" (for an iPhone app this would be different, more like @"/Users/andrewf/Library/Application Support/iPhone Simulator/User/Applicatons/(unique id)/MyApp.app/Resources/Plates.plist"), and it is inside the Resources folder of your app that pathForResource: is looking.

What this implies is that your resource is not in the "Copy Bundle Resources" phase of your build target. You need to drag it from the Groups and Files area to inside that phase.