如何访问项目内的本地文件
我想向我的应用程序添加一些静态文件(图像、二进制文件等)。我已将它们放在名为 Resources
的文件夹下,并将其添加到我的 XCode 项目中。
接下来,我将这些文件添加到项目设置的 Build Phases
选项卡中的 Copy Bundle Resources
中。
但是,我似乎无法以正确的方式引用它们。
例如,读取二进制文件:
NSInputStream *is = [[NSInputStream alloc] initWithFileAtPath:@"data.bin"];
if(![is hasBytesAvailable]) NSLog(@"wrong");
这总是失败&打印 wrong
我尝试使用 NSData initWithContentsOfFile:
类似的方法,但这甚至不会执行。另一种尝试是使用 [NSBundle mainBundle]
但这也没有完全执行。
我是 iOS 新手,请帮助我访问本地文件!任何帮助将不胜感激。
谢谢你,
I want to add some static files (image, binary, etc...) to my app. I've placed them under a folder named Resources
and have added it to my XCode project.
Next, I have those files added to the Copy Bundle Resources
in the Build Phases
tab in the project settings.
However, I can't seem to refer to them in the right way.
For instance, reading a binary file:
NSInputStream *is = [[NSInputStream alloc] initWithFileAtPath:@"data.bin"];
if(![is hasBytesAvailable]) NSLog(@"wrong");
This always fails & prints wrong
I tried a similar approach with NSData initWithContentsOfFile:
but this wouldn't even execute. Another attempt was to use [NSBundle mainBundle]
but this also didn't execute fully.
I'm new to iOS please help I can access my local files! Any help would be appreciated.
Thank you,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要确保在正确的位置访问该文件。 Xcode 将您的资源文件放置在应用程序的“应用程序包”的 Resources 目录中。有很多方法可以把它们挖出来。
一种常见的方法是获取捆绑包中文件的路径名:
如果捆绑包中的非标准位置有其他文件,则 pathForResource 有一些变体,可以让您指定目录名称。
如果您想查看模拟器正在使用的硬盘驱动器上的实际位置以便您可以检查它,您可以说:
在 Xcode 文档库中搜索“捆绑编程指南”即可开始。 :-)
You need to ensure that you're accessing the file in the right place. Xcode places your resource files in the application's "application bundle" in the Resources directory. There are many ways to dig 'em out.
A common way is to get the pathname of a file in your bundle:
If you have other files in nonstandard places in your bundle, there are variations to pathForResource that let your specify a directory name.
If you want to see the actual location on your hard-drive that the simulator is using so you can inspect it, you can say:
Search for the "Bundle Programming Guide" in the Xcode documentation library to get started. :-)
为此使用 NSBundle 类。例如:
Use
NSBundle
class for that. For Example:事实上,即使您“initialiseWithFileAtPath”,也需要调用[is open]。我认为初始化会自动为您打开文件,但事实并非如此。
Indeed calling [is open] is needed even though you "initialiseWithFileAtPath". I would think the initialisation would automatically open the file for you, but it doesn't.