如何访问项目中的本地文件 [英] How to access local files within project

查看:386
本文介绍了如何访问项目中的本地文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用中添加一些静态文件(图像,二进制等)。我把它们放在一个名为 Resources 的文件夹下,并将它添加到我的XCode项目中。

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.

接下来,我将这些文件添加到项目设置中 Build Phases 选项卡中的复制包资源

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

我尝试了类似的方法 NSData initWithContentsOfFile:但这甚至都不会执行。另一种尝试是使用 [NSBundle mainBundle] 但这也没有完全执行。

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.

我是新的到iOS请帮助我可以访问我的本地文件!任何帮助将不胜感激。

I'm new to iOS please help I can access my local files! Any help would be appreciated.

谢谢,

推荐答案

你需要确保您在正确的位置访问该文件。 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:

NSBundle *mainBundle = [NSBundle mainBundle];
NSString *myFile = [mainBundle pathForResource: @"data" ofType: @"bin"];

如果您的捆绑包中有非标准位置的其他文件,则 pathForResource 让你指定一个目录名。

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:

NSLog(@"Main bundle path: %@", mainBundle);
NSLog(@"myFile path: %@", myFile);

在Xcode文档库中搜索Bundle Programming Guide以开始使用。 : - )

Search for the "Bundle Programming Guide" in the Xcode documentation library to get started. :-)

这篇关于如何访问项目中的本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆