best way to load an image library of iphone nsmuta

2019-06-14 08:19发布

问题:

I have created an app which has a library of images. I have imported the images in to my resources folder in Xcode and am currently loading them in to an array in the appDelegate when the app loads. This is happening each time. I am now worried that as the library grows the app will run out of memory. Is there a better way of loading these?

the structure is

Library > category > image list > image

I have an NSMutableArray called mainLibrary which I then add another nsmutablearray for each category. For example

NSMutableArray *arrHome = [[NSMutableArray alloc] initWithObjects:  @"Home",                           
    [NSDictionary dictionaryWithObjectsAndKeys: [NSString stringWithFormat:@"%@/%@", resourcePath, @"alarm_clock.png"], @"image_path", @"Alarm Clock", @"title", nil],
    [NSDictionary dictionaryWithObjectsAndKeys: [NSString stringWithFormat:@"%@/%@", resourcePath, @"bathtub.png"], @"image_path",@"Bathtub", @"title", nil],

    nil];
[mainLibrary addObject: arrHome];

The above is for the "home" category and contains only two images. For other categories, I have the NSDictionary line for each image - there can be up to 100 images in each category.

If I am loading in 50mb+ of images to an array will this cause the app to become unresponsive - or more than likely, simply crash as it uses more of the 24mb (ish) allowance per app??

I am wondering whether I should do the above code and read in to the array ONCE a category has been selected - but that might then cause it to stall for the user.

Any thoughts?!

ps) I also need to have a think about Retina display. With 600+ images, duplicating them would mean my binary size would rocket!!

回答1:

compose your path dictionaries/arrays using strings, then load/unload images as needed (load lazily), if you need such a structure to interface with in your program.

600 HQ images will exceed the memory limits, and it's wasteful because the user will see how many of these images at a given time? resources are quite limited, and hq images require a lot of space.

if you have to display a bunch of thumbnails, those may be shrunk and exported easily enough so you can display all the images in a reasonable amount of time, while using a rational amount of memory (again, just load lazily where possible and release the image when not very easily viewed).



回答2:

A while ago I ran some tests for an app I was working on. Loading 5000 images in succession:

[UIImage imageWithData:...] // 44.8 seconds

[UIImage imageWithContentsOfFile:...] // 52.3 seconds

[[UIImage alloc] initWithContentsOfFile:…] // 351.8 seconds

[UIImage imageNamed:...] // hung due to caching

Using the paths to the files is obviously the way to go. Obviously memory management will be key in your case.



回答3:

Why not use [UIImage imageNamed:IMAGE_NAME] directly ? It has a good memory management inside.