xcode 捆绑包和文件访问
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/916824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bundles and file access
提问by John Muchow
I've adding a series of folders to my project (using the Add existing file option). This results in the folder contents being shown in Xcode as a blue folder.
我在我的项目中添加了一系列文件夹(使用添加现有文件选项)。这导致文件夹内容在 Xcode 中显示为蓝色文件夹。
The following works:
以下工作:
NSString *imageName = [NSString stringWithFormat:@"/File-03/images/image-%02d.jpg", imageIndex];
return [UIImage imageNamed:imageName];
However, I want to switch to using imageWithContentsOfFile
so the images are not cached.
但是,我想切换到使用,imageWithContentsOfFile
以便不缓存图像。
The code below returns nil
for the image:
下面的代码返回nil
图像:
return [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"/File-03/images/image-%02d.jpg", imageIndex]];
I also tried accessing the imageWithContentsOfFile
using a bundle, no go.
我还尝试imageWithContentsOfFile
使用捆绑包访问,但不行。
What am I missing here?
我在这里错过了什么?
回答by epatel
To access and store files on the iPhone I recommend reading this.
要在 iPhone 上访问和存储文件,我建议阅读这篇文章。
Erica Sadun has also written a nice shortyabout accessing file within a app bundle.
Erica Sadun 还写了一篇关于在应用程序包中访问文件的简短文章。
Note that how files are organized in Xcode does not show how they will end up in the app bundle. The best way is to select the app bundle in the Finder and CTRL-click and select Show Package Content.
请注意,文件在 Xcode 中的组织方式并未显示它们在应用程序包中的最终位置。最好的方法是在 Finder 中选择应用程序包,然后按住 CTRL 键单击并选择Show Package Content。
回答by John Muchow
Okay, I figured out one way in code to get what I needed:
好的,我想出了一种代码方法来获得我需要的东西:
NSString *dir = [NSString stringWithFormat:@"File-03/images", imageIndex];
NSString *file = [NSString stringWithFormat:@"image-%02d", imageIndex];
NSString *path = [[NSBundle mainBundle] pathForResource:file ofType:@"jpg" inDirectory:dir];
return = [UIImage imageWithContentsOfFile:path];
The trick was to inDirectoryin the bundle call.
诀窍是在捆绑调用中使用inDirectory。
回答by Andrew Pouliot
The problem with your imageWithContentsOfFile code is that you're assuming that /
is the root of the bundle, when it's the root of the FS!
你的 imageWithContentsOfFile 代码的问题是你假设它/
是包的根,当它是 FS 的根时!
So, pathForResource:ofType:inDirectory:
is probably the easiest way to get the path you need.
因此,pathForResource:ofType:inDirectory:
可能是获得所需路径的最简单方法。
Otherwise, you can get the root of the bundle and prefix that to your paths.
否则,您可以获得包的根目录并将其作为路径的前缀。