I'm using the following method to download images for artists in an array. I use LastFm to get the images, then store them in ESCache.
self.imageDownloadingQueue = [[NSOperationQueue alloc] init];
self.imageDownloadingQueue.maxConcurrentOperationCount = 1;
self.artworkCache = [[ESCache alloc] initWithName:@"artworkCache" error:nil];
NSArray *artists = // get artists using relevant framework;
for (MPMediaItemCollection *collection in artists){
[self.imageDownloadingQueue addOperationWithBlock:^{
@autoreleasepool {
MPMediaItem *item = [collection representativeItem];
NSString *artistString = [item valueForProperty:MPMediaItemPropertyAlbumArtist];
BOOL isCachedImage = [self.artworkCache objectExistsForKey:artistString];;
if (!isCachedImage){
[[LastFm sharedInstance] getInfoForArtist:artistString successHandler:^(NSDictionary *result) {
if ([artistString isEqualToString:[[result objectForKey:@"_params"] objectForKey:@"artist"]]) {
NSURL *imageURL = [result objectForKey:@"image"];
if (imageURL){
NSData * data = [NSData dataWithContentsOfURL:imageURL];
UIImage *artistImage = [UIImage imageWithData:data];
[self.artworkCache setObject:artistImage forKey:artistString];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[downloadButton setTitle:artistString forState:UIControlStateNormal];
[downloadButton setBackgroundImage:artistImage forState:UIControlStateNormal];
}];
artistImage = nil;
}
else{
UIImage *newArtworkImage = // get placeholder image;
if (newArtworkImage != nil){
[self.artworkCache setObject:newArtworkImage forKey:artistString];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[downloadButton setTitle:artistString forState:UIControlStateNormal];
[downloadButton setBackgroundImage:newArtworkImage forState:UIControlStateNormal];
}];
newArtworkImage = nil;
}
}
}
else{
}
} failureHandler:^(NSError *error) {
}];
}
}
}];
}
I see my memory usage increasing in Xcode to just over 200mb, then my app crashes with the following error:
2015-01-18 20:56:36.479 Mezzo[1481:39314] Received memory warning. Mezzo(1481,0x105254000) malloc: * mach_vm_map(size=147456) failed (error code=3) * error: can't allocate region *** set a breakpoint in malloc_error_break to debug
It loops through the first 50 or so artists, gets their images (I can see downloadButton
change) but then it crashes. I'm not sure how to deal with the increasing memory usage issue. I set the images to nil
after I've stored them and I put everything in an autoreleasepool
.
How else would I reduce memory usage as it loops through this array? Any help would be much appreciated. Thanks.