Вопрос

I am trying to load more than 100 images from the bundle, however recently I was just curious what is the best practice to load the images dynamically from the bundle. Will custom Images.xcassets allow me to do such task? How can I dynamically load NSArray?

Это было полезно?

Решение

To start with my answer I will recommend, DON'T do it.

Its really an overkill for your app to load 100 images and to store them in memory, at once, and the app would definitely go under some memory pressure.

In Xcode 5, .xcassets is still the best place to keep your images in app bundle. For further details you might be interested in Apple Asset Catalog documentation. However, rather than loading and storing images to NSArray, I would recommend you to store their identifiers (actually the image names as added to .xcassets) in the array. Also it would be helpful if you store the image identifiers to some NSString* const beforehand.

So your coding structure should look something like the following:

//image names
NSString* const kImage1 = @"image1";
NSString* const kImage2 = @"image2";
NSString* const kImage3 = @"image3"; 
//...etc

NSArray* imageIdentifiers = @[kImage1, kImage2, kImage3,...];

//...

And then to load individual image from bundle you could use:

UIImage* img = [UIImage imageNamed:kImage3]; //loads image3 from bundle and caches

Or to traverse through all images you might use:

for (NSString* identifier in imageIdentifiers) {
    @autoreleasepool { //make sure your image data gets disposed after use
        UIImage* img = [UIImage imageNamed:identifier];
        //... use img, etc.
    }
}

And finally, imageNamed: method of UIImage class, caches an image in system cache. So you won't have to worry about reloading it from file, if you reuse one.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top