patchrail
patchrail

Reputation: 2007

pathForResource returns null

I'm trying to load some .applescript files in my project.

Copied them into the "Supporting Files" directory like this:

enter image description here

and tried to access them:

NSBundle *bundle = [NSBundle mainBundle];
NSLog(@"Resource path for test.applescript: %@", [bundle pathForResource:@"test" ofType:@"applescript"]);

pathForResource always returns null.

Both files are correctly imported in xcode. The target membership is my app. Solutions from similar questions didn't really help

What am i doing wrong?

Upvotes: 41

Views: 24462

Answers (6)

Cynichniy Bandera
Cynichniy Bandera

Reputation: 6103

Just in case you have this issue on the app start, note that [bundle pathForResource] will not work earlier than in the applicationDidFinishLaunching.

Update: Also, make sure you are running it from the main thread.

Upvotes: 0

Ahmad Ishfaq
Ahmad Ishfaq

Reputation: 914

For all those who are still getting a nil path and the file is added in "Copy Bundle Resources" just remove the file from Copy Bundle Resources and than add again.

Upvotes: 5

agovan
agovan

Reputation: 63

Great response from Zaph above, but I noticed when I was doing it there's quicker way, at least in Xcode 6.1.

if you single click the file (eg. test.applescript) and have the right menu of Xcode open, you'll see a section called "Target Membership". Make sure that the right target (as in the one you're using the script with) is selected and it'll do the same job as adding the file under "Copy Bundle Resources"

Also, not entirely relevant but in case you're loading from several different places, or you are inheriting this class. You shouldn't really use

[NSBundle mainBundle];

instead use

[NSBundle bundleForClass:[self class]];

That means you don't have to worry about where you are on the method call it'll take the resource from the appropriate items associated with the target you're running. Great for making libraries and reusable calls ;)

Upvotes: 1

Jon
Jon

Reputation: 7918

In addition to what Zaph said, be sure that you are not running in 'Release' mode.

There was a time where I forgot to change that setting back, and the symbols were stripped, thus making NSBundle incapable of resolving the path.

Upvotes: 0

beryllium
beryllium

Reputation: 29767

Does your image assume that that file in some folder?

Try pathForResource:ofType:inDirectory: method in this case:

NSLog(@"Resource path for test.applescript: %@", [bundle pathForResource:@"test" ofType:@"applescript" inDirectory:@"folder/Supporting Files");

Upvotes: 0

zaph
zaph

Reputation: 112873

In the Xcode target "Build Phases" add the file under "Copy Bundle Resources"".

Upvotes: 160

Related Questions