How do I enumerate and load resources in an iPhone app?

99封情书 提交于 2020-01-04 06:35:35

问题


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];
}

However, I'm trying to avoid kNumImages entirely. Is there a way to run a regex or something on resources?


回答1:


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];
  }
}

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.



来源:https://stackoverflow.com/questions/513480/how-do-i-enumerate-and-load-resources-in-an-iphone-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!