Reputation: 101
I have a UICollectionView / UITableView showing images, as I scroll through the images the memory allocation gradually grows and eventually crashes my device.
To create my objects for the UICollectionView / UITableView I have a builder class where I generate my objects from JSON (Included in this JSON is a Base64 string of an image). After creating these objects I put them into an NSArray and then pass them to the UICollectionView / UITableView.
The memory allocation issue happens when (in the builder class) I create my UIImage from Base64:
NSData *dataFromString = [[NSData alloc] initWithBase64EncodedString:base64 options:0];
UIImage *image = [[UIImage alloc]initWithData:dataFromString];
But if I create my UIImage from a png/jpg (again in the builder class) I have no issues (i.e. the memory allocation does not grow):
UIImage *image = [UIImage imageNamed:@"image.png"];
I used instruments and there appear to be no memory leaks, and when I dismiss the UICollectionView / UITableView the memory footprint goes down, but Im at a loss as to why the difference seems to be the use of Base64.
Thanks in advance
Carl.
Upvotes: 0
Views: 379
Reputation: 101
I solved this issue by creating a tempFileManger class, I then write the UIImages to a temporary directory as PNG:
NSString *path = [tempDir stringByAppendingPathComponent:imageObject.title];
NSData *data = UIImagePNGRepresentation(imageObject.image);
Then in my cellForItemAtIndexPath method I retrieve using the following:
NSString *path = [tempDir stringByAppendingPathComponent:imageObject.title];
UIImage *image = [UIImage imageWithContentsOfFile:path];
Once I have finished using the images I delete all the images in the temp folder using my tempFileManagerClass.
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:tempDir error:nil];
for (NSString *filename in contents) {
[[NSFileManager defaultManager] removeItemAtPath:[tempDir stringByAppendingPathComponent:filename] error:NULL];
}
Upvotes: 0