本文介绍了URLForResource 返回 nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何使用 xcode 以及如何为 Mac 编写应用程序.

I'm in the process of learning how to use xcode and how to write applications for the Mac.

所以,我有一个简单的屏幕保护程序,可以加载一个运行良好的外部文件.我决定最好在应用程序中嵌入 html 源代码以减少外部依赖.

So, I have a simple screensaver that loads an external file which works fine. I decided that it would be better to embed the html source in the application to reduce the external dependancies.

我将 HTML 文件拖到资源文件夹中,它在顶层,没有子文件夹或任何东西.

I dragged the HTML file to the resources folder, it's at the top level there's no sub folder or anything.

我确保添加到目标中有我的应用程序,同时选择创建文件夹引用"和如果需要复制文件".我使用以下内容获取文件的 url,但它返回 nil

I made sure the Add to targets had my application in it, along with selecting 'create folder references' and 'copy files if needed'. I use the following to get the url to the file, but it returns nil

    NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"embedded" withExtension:@"html"];


 System Preferences[10185]: fileUrl returned (null)

我已经阅读了所有其他类似问题的 SO 问题,但似乎没有任何修复程序适用.我已经通过并检查了它们.

I've read through all the other SO issues for the similar problems but none of the fixes seem to apply. I've gone through and checked them.

如果我显示最终构建的包内容,embedded.html 就在那里.我是否遗漏了一些非常明显的东西?

If I show the package contents of the final build the embedded.html is in there. Am I missing something really obvious?

编辑添加

在构建阶段,它列在复制捆绑资源中

In build phases it's listed in Copy Bundle Resources

xcode 版本为 6.1.1

xcode version is 6.1.1

推荐答案

经过一些相当大的挖掘和一点点运气,我发现

After some considerable digging and a smidgeon of luck I found that

    NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"embedded" withExtension:@"html"];

不正确,我应该使用

is incorrect and I should be using

    NSURL *fileUrl = [[NSBundle bundleForClass:[self class]] URLForResource:@"embedded" withExtension:@"html"];

相反.

NSBundle bundleForClass:[self class] 而不是 NSBundle mainBundle 将允许访问屏幕保护程序包.

i.e. NSBundle bundleForClass:[self class] and not NSBundle mainBundle will give access to a screensaver bundle.

可能很明显,但前提是你知道;)

Might be obvious, but only if you know ;)

参见 Apple Developer NSBundle 类参考

这篇关于URLForResource 返回 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 04:09