NSBundle pathForResource is NULL

前端 未结 9 928
感情败类
感情败类 2020-11-29 04:41

I\'m creating a simple application with xcode and objc and I need to load an NSDictionary from a file, but I can\'t get the path to the file using NSBundle:

         


        
相关标签:
9条回答
  • 2020-11-29 04:56

    Make sure you spell your resource's file name properly. I just learned that the hard way. :)

    0 讨论(0)
  • 2020-11-29 04:59

    In my case (executing XCTestCase) for some reason resources were stored in non-main Bundle. I fixed the problem by checking first which bundle test class belongs to:

    [[NSBundle bundleForClass:[self class]] pathForResource:@"Config" ofType:@"plist"];
    

    Hopefully this can help someone else as well.

    0 讨论(0)
  • 2020-11-29 05:02

    So here's the solution for this problem after I got the source:

    I didn't really pay attention to the posted screenshot, but the target is of type "Command-line Tool"... and since those don't have a bundle [NSBundle mainBundle] of course returns nil. It's pretty misleading that Xcode doesn't complain that it can't execute the "Copy Bundle Resources" step, it just silently skips it.

    Solution is simply to add a new target, of type "Application" so a bundle-based application is generated. Then check the Target Membership checkboxes for all sources and resources for this new target. The plist paths are correctly resolved then.

    0 讨论(0)
  • 2020-11-29 05:05

    Since I have googled here, did not find the answer, but then discovered it by myself, I'll leave it here...

    I had 2 files: tray.png and tray@2x.png for Retina. The files were added to "Copy Bundle Resources" automatically.

    But:

    [[NSBundle mainBundle] pathForResource:@"tray" ofType:@"png"];
    

    did not return the file actually copied to the bundle! The reason was: IDE created one TIFF file tray.tiff (joint tray.png and tray@2x.png), so ... ofType:@"tiff"] helped!

    0 讨论(0)
  • 2020-11-29 05:06

    I encountered this issue today with a Command Line project.

    Luckily, the solution is easy. Simply go to "Build Phases", click on "+" and add a new "Copy Files" phase. Choose "Resources" as Destination, and add any files you want to use.

    Now you can still use [NSBundle mainBundle] and it should work!

    0 讨论(0)
  • 2020-11-29 05:07

    My problem and solution are very similar to Dmitriy Isaev's ones. I have tried to get path for a xib file. Both calls (in Swift) pathForResource("myfile", ofType: "xib") and pathForResource("myfile.xib", ofType: nil) are failed.

    The solution is to use extension "nib" instead:

    pathForResource("myfile", ofType: "nib")
    
    0 讨论(0)
提交回复
热议问题