SimplyKiwi
SimplyKiwi

Reputation: 12444

Create array out of all images in app?

Is it possible to create a NSArray out of all .png, .jpg, and .jpeg that are all in my app? I know it is possible to do it to a certain type like only .pngs but I am not sure how to do it to all images in my app.

I would rather not have lots of conditionals so how could I do this easily?

Thanks!

Edit1:

// Do any additional setup after loading the view, typically from a nib.
NSString * pathToImages = [NSString stringWithFormat: @"%@/images", [[NSBundle mainBundle] resourcePath]];
NSFileManager *localFileManager= [[[NSFileManager alloc] init] autorelease];
NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:pathToImages];
NSString *file;
NSLog(@"level1");
while (file = [dirEnum nextObject]) {
    NSLog(@"level2");
    if(file)
    {
        NSLog(@"level3");
        [imagesArray addObject:file];
    }
}

Upvotes: 0

Views: 995

Answers (1)

Michael Dautermann
Michael Dautermann

Reputation: 89509

Depends on how you want to store images in your array. Do you want file references or actual UIImage objects?

Anyways... if you kept all your images in a "images" folder in your app's Resources directory, why not try something like:

NSString * pathToImages = [NSString stringWithFormat: @"%@/images", [[NSBundle mainBundle] resourcePath]];
NSFileManager *localFileManager= [[NSFileManager alloc] init];
NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:docsDir];
NSMutableArray * arrayOfImages = [[NSMutableArray alloc] initWithCapacity: 1];
NSString *file;
while (file = [dirEnum nextObject]) {
    // let's assume that all objects in here are valid images
    UIImage * newImage = [UIImage imageWithContentsOfFile: file];
    if(newImage)
    {
        [arrayOfImages addObject: newImage];
    }
}

By the way... if you are loading a lot of images (especially high rez ones), you're likely to hit didReceiveMemoryWarning calls in your view controllers.

Upvotes: 1

Related Questions