【问题标题】:pathForResource ofType returns nilpathForResource ofType 返回 nil
【发布时间】:2014-02-24 21:34:13
【问题描述】:

这是我正在使用的代码。

NSString* path = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"plist"];

if(path == nil)
{
NSLog(@"file not found");
}

当我运行它时,它会打印在控制台中找不到的文件。

我的 file.plist 位于我的可可项目的支持文件夹中。 mainBundle 在哪里查找文件。这让我很困惑。我知道它会查找 .app 文件,但是在开发应用程序时 mainBundle 会在哪里查找?

【问题讨论】:

    标签: objective-c null nsbundle mainbundle


    【解决方案1】:

    pathForResource:ofType: 仅在 Resources 文件夹(和本地化文件夹)中查找。如果要将文件放入捆绑包中的专用文件夹,则需要使用 pathForResource:ofType:inDirectory: 并提供目录名称。

    【讨论】:

    • 我厌倦了使用 inDirectory 路径和项目内部文件的本地路径,如下所示: NSString *path = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"plist" inDirectory :@"/Users/joshuablevins/Documents/Xcode/Tutorials/plist tut/plist tut"];但它仍然说找不到文件。
    • inDirectory: 您只需传递捆绑包中的文件夹名称(支持文件的文件夹名称),而不是完整路径。这应该是您在复制项目构建阶段设置的文件夹名称
    • 如果你有一个文件的完整显式路径,那么它通常不在你的包中并且你不使用 NSBundle 来访问它
    • 应该是拷贝文件还是拷贝bundle资源构建阶段?
    • 复制文件(因为它允许您设置要复制到的文件夹名称)。复制捆绑资源将所有内容放在Resources 文件夹中
    【解决方案2】:

    如果您找到的NSBundle 是您想要的:

    NSBundle *yourTargetBundle = [NSBundle mainBundle];
    
    or
    
    NSBundle *yourTargetBundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] 
    URLForResource:@"YourCustomBundleName" withExtension:@"bundle"]];
    

    并得到nil结果使用函数:pathForResource: ofType:。然后就可以登录yourTargetBundle下资源的paths了:

    // Given that your resource type is .png and have no sub dir
    NSArray *resoursePaths = [yourTargetBundle pathsForResourcesOfType:@"png" inDirectory:nil];
    NSLog(@"resoursePaths == %@",resoursePaths);
    

    它将记录所有png 类型的资源路径。可以获取image对象使用:

    targetImg = [[UIImage alloc] initWithContentsOfFile:@"OnePngPathYouChose"];
    

    我认为上述方法是解决return nil 情况的一种方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-23
      • 2012-02-27
      • 1970-01-01
      • 2023-03-03
      • 2015-02-25
      • 2012-03-09
      • 2017-05-29
      • 1970-01-01
      相关资源
      最近更新 更多