2

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 imageNamed:@"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?

2 Answers 2

3

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]];
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the solution. How do I set the directory? When I try to add @"images" it crashes the app.
how do you set this directory
2

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

1 Comment

Thanks. Your solution looks good. It doesn't load any images, however... is climbing_%03.jpg correct?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.