Search code examples
iosobjective-cxcodeuiimageviewnsdata

DidRecieveMemoryWarning called after viewDidAppear when displaying large image file


My app has terminated due to memory pressure when I load a particular page. I am using an NSURLRequest to get data and load an image. I placed breakpoints throughout my code and traced the first didRecieveMemoryWarning call to right after viewDidAppear. Here is the code I am using to load the image:

NSError *error = nil;
NSURLResponse *response = nil;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.img]];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
UIImage *img = [[UIImage alloc] initWithData:data];
self.ImgView.image = img;
[self.scrollView addSubview:self.ImgView];

Some facts about the data that I have gathered:

  1. Image is 5,184px × 3,456px (scaled to 1,008px × 672px) online
  2. I am placing the image into a 320 x 320 UIImageView
  3. The NSData object data is 5,360,785 bytes

How can I correct this problem? Is the app just not able to handle the data, or is the imageView not able to scale the image? The image appears onscreen, but the app crashes a bit after the screen loads, whether you stay on that page or leave it.


Solution

  • Try to load the image once the view is loaded & before assigning to imageview scale down the image little bit. This avoid memory warning.

    For Ref: NSData to UIImage

    for resizing image: How to scale down a UIImage and make it crispy / sharp at the same time instead of blurry?