Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 432
andrewdotcoza Avatar asked Dec 07 '22 05:12

andrewdotcoza


2 Answers

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.

like image 106
Dave DeLong Avatar answered May 16 '23 08:05

Dave DeLong


I have found the problem!

The .plist file was included in the target correctly.

When the .plist was originally created, I named the file "plates.plist". Immediately after creating the file, I renamed it to "Plates.plist", and this is what I used henceforth.

Even though the file was named "Plates.plist" in my resources folder, in the target section and in the iPhone Simulator location mentioned above, the file was named "plates.plist". Curiously, the contents of the file was still updated correctly.

Now that I have changed the code to refer to "plates.plist", and renamed the file in the Resources folder to the same for good measure, everything works. I can only assume that this is a bug in the iPhone SDK.

like image 25
andrewdotcoza Avatar answered May 16 '23 08:05

andrewdotcoza