views:

1185

answers:

2

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?

+10  A: 

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.

Squeegy
What if I have mixed image types?They will all have names like image#.ext, but ext may vary.
Sam
Oh, I think I have an answer for that: paths = [[NSBundle mainBundle] pathsForResourcesOfType:nil inDirectory:nil];and then filter out the ones I don't want in the for loop.
Sam
If you pass nil as the extension string it will return all files, which you can then test the names of from there. But this may have performance issues depending on what you are doing and how many file you have. Or you could use 2 loops, one for each extension type.
Squeegy
The single loop should be faster since pathsForResourcesOfType:inDirectory: has to iterate through each file to compare its extension against the type parameter. YMMV
rpetrich
A: 

Minor nit on @Squeegy's code:

The use of [[filename componentsSeparatedByString:@"/"] seems inefficient. Wouldn't it be better to use [filename lastPathComponent]?

escouten