Reputation: 3397
As I have received memory warning because I have large images from server(Around 10mb each). I resized all images and then filled it into collection view. My issue is when I scroll collection view it got stuck and taking more time to load. I am using following code.Item.b_imageUrl is path of server. I am using NSDictionary.
UIImage * image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:item.b_imageUrl]]];
CGSize sacleSize = CGSizeMake(100, 100);
UIGraphicsBeginImageContextWithOptions(sacleSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, sacleSize.width, sacleSize.height)];
UIImage * resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[cell.imgV_b_image setImage:resizedImage];
Also when I checked it in instruments allocation tool my overall bytes going crazy(700mb-its very big)
How can I scroll smoothly with no memory warning...? Thanks for any help.
Upvotes: 0
Views: 436
Reputation: 24247
Ideally you want your server to give you resized images but if that's not possible here are my ideas:
Your image resizing code does not belong in a view controller. Ideally you should be downloading these images from a network service and you could either add custom image resizing requests to the network (similar to how AFNetworking 1.0 had AFImageRequestOperation). This way all your controller needs to do is ask for an image of a particular size and the network service will queue the image operation and return a resized image.
Another concern of mine is where you are resizing your images. It looks to me like this is happening in the main thread. Don't. When the image is downloaded you should resize the image to the background thread and let the controller dispatch the flow to the main thread so that the image can be binded to the image view.
You should also be caching these images somewhere on the device. It's a poor user experience to have to always re-download what you've already seen. Perhaps somewhere inside the NSCachesDirectory()
Don't forget that while the images are downloading the user can be anywhere in the collection view. You should take it upon yourself to either cancel image requests that have been scrolled off screen or at least use a LIFO queue so that the most recently viewed image requests get priority. So when your image finishes you can query -[UICollectionView cellForItemAtIndexPath:]
to see if the cell is still on screen
Upvotes: 1