简体   繁体   English

Objective-C-pathForResource始终返回nil

[英]Objective-C - pathForResource always returns nil

I want to read a .plist file from a certain directory but pathForResource always returns nil , meaning it can't find the file I'm looking for. 我想从某个目录中读取.plist文件,但pathForResource始终返回nil ,这意味着它找不到我要查找的文件。 This is what I'm using to create the path. 这就是我用来创建路径的东西。 The file is stored in the Project folder. 该文件存储在Project文件夹中。

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"test" ofType: @"plist"];

What am I doing wrong? 我究竟做错了什么? And how can I access a plist file from a directory which is not part of the project? 以及如何从不属于项目的目录中访问plist文件? This is for a macOS command line tool. 这是用于macOS命令行工具的。

As the comments pointed out, you can't use +[NSBundle mainBundle] unless your app is structured with a .app/ bundle. 正如评论所指出的那样,除非您的应用程序是由.app/包构成的,否则不能使用+[NSBundle mainBundle] If you are making a command line app (meaning a single binary), then to read in the path, you need to figure out the location of the file a different way. 如果要制作命令行应用程序(表示单个二进制文件),则要读取路径,您需要以其他方式找出文件的位置。

When you say "The file is stored in the Project folder", I'm not quite sure what you mean. 当您说“文件存储在Project文件夹中”时,我不太确定您的意思。 Surely you won't expect the .plist file to be hanging out in /usr/bin or wherever you end up deploying the binary! 当然,您不会期望.plist文件会挂在/ usr / bin或您最终将二进制文件部署到的任何地方! If the plist you're reading needs to ship with the app, then you should be using a bundle. 如果您正在阅读的plist需要随应用程序一起提供,则您应该使用捆绑软件。 If instead you generate the plist while running the app somehow (either by downloading it from the web or by building it up through storing things incrementally), then you should create a subfolder for your app in the Application Support directory which you can query for the .plist. 如果改为以某种方式运行应用程序时生成plist(通过从Web下载或通过逐步存储内容来构建plist),则应在Application Support目录中为应用程序创建一个子文件夹,您可以查询该子文件夹的.plist。

Once you have the .plist path, you can use +dictionaryWithContentsOfFile: to read it in. 一旦有了.plist路径,就可以使用+dictionaryWithContentsOfFile:来读取它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM