Create array from images in folder?
I would like to make my code a little better.
This is my array:
//All images - Add images to the queue
imagesQueue = [[NSMutableArray alloc] init];
[imagesQueue addObject:[UIImage imageNamed:@"climbing_001.jpg"]];
[imagesQueue addObject:[UIImage imageNamed:@"climbing_002.jpg"]];
[imagesQueue addObject:[UIImage im开发者_Go百科ageNamed:@"climbing_003.jpg"]];
[imagesQueue addObject:[UIImage imageNamed:@"climbing_004.jpg"]];
All my images are inside an images folder in my resources.
Is there a way to automatically create an array from all the images in that folder?
NSBundle has a number of methods to help here. An example:
NSArray* imagePaths = [[NSBundle mainBundle] pathsForResourcesOfType:@"jpg" inDirectory:imagesFolder];
imagesQueue = [[NSMutableArray alloc] initWithCapacity:imagePaths.count];
for (NSString* path in imagePaths)
{
[imagesQueue addObject:[UIImage imageWithContentsOfFile:path]];
}
Use NSFileManager
methods to discover the content of a directory.
Use NSBundle
's resourcePath
method to get this given path to the resources folder uour images are in, or directly the paths to those files using methods such as pathsForResourcesOfType:inDirectory:
.
But I am not sure that base your code on the contents of your resources directory is the right approach. The best solution is probably to still setting the names of images in your code (instead of iterating into your folder contents), and set the images using a loop:
for(int i=0;i<4;++i) {
NSString* imageName = [NSString stringWithFormat:@"climbing_%03d.jpg",i+1];
[imagesQueue addObject:[UIImage imageNamed:imageName]];
}
精彩评论