如何在iPhone应用程序中枚举和加载资源? [英] How do I enumerate and load resources in an iPhone app?
问题描述
我试图在资源中填充一个图像集合的NSArray。但是,为了最大的灵活性,我试图避免硬编码文件名,甚至有多少文件。
I'm trying to populate an NSArray with a collection of images in Resources. However, for maximum flexibility, I'm trying to avoid hard-coding the filenames or even how many files there are.
通常,我会做这样的例子从苹果的示例代码:
Normally, I'd do something like this example from the sample code at apple:
kNumImages = 5; //or whatever
NSMutableArray *images;
for (i = 1; i <= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:@"image%d.jpg", i];
[images addObject:[UIImage imageNamed:imageName];
}
但是,我试图完全避免kNumImages。
However, I'm trying to avoid kNumImages entirely. Is there a way to run a regex or something on resources?
推荐答案
这里是一个片段,只是从我的iPhone应用程序
Here's a snippet that does just that from my iPhone app
// Load item icons
paths = [[NSBundle mainBundle] pathsForResourcesOfType:@"png" inDirectory:nil];
for (NSString *filename in paths) {
filename = [[filename componentsSeparatedByString:@"/"] lastObject];
if ([filename hasPrefix:@"ItemIcon"]) {
[UIImage imageNamed:filename];
}
}
它遍历所有具有png扩展名的资源,文件名以ItemIcon开头,然后加载到UIImage的内置缓存中。
It loops through all resources that have a png extension, and it the filename begins with "ItemIcon" then it loads into UIImage's built in cache.
如果您在特定目录中有它们,则需要指定间接:
If you have them in a specific directory, you will need to specify the indirectory: argument.
这篇关于如何在iPhone应用程序中枚举和加载资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!