Background:
Inspired from Apple's sample code ScrollViewSuite, I've created a view controller class that shows picture thumbnails and one selected picture. The hierarchy of controls for the "selected" picture is something like this:
--> UIView
--> UIScrollView
--> UIImageView
Following code is used to put the UIScrollView onto the view:
imageScrollView = [[UIScrollView alloc] initWithFrame:frame];
[imageScrollView setBackgroundColor:[UIColor clearColor]];
[imageScrollView setDelegate:self];
[imageScrollView setBouncesZoom:YES];
[[self view] addSubview:imageScrollView];
... and following code is used to configure and add UIImageView to the UIScrollView:
// Custom method to return a UIImage from a URL string
UIImage *image = [UIImage newImageWithContentsOfURL:imageURL];
// first remove previous image view, if any
[[imageScrollView viewWithTag:MAIN_IMAGE_TAG] removeFromSuperview];
// set the new image view
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[imageView setDelegate:self];
[imageView setTag:MAIN_IMAGE_TAG];
[imageScrollView addSubview:imageView];
[imageScrollView setContentSize:[imageView frame].size];
// choose minimum scale so image width fits screen
float minScale = [imageScrollView frame].size.width / [imageView frame].size.width;
[imageScrollView setMinimumZoomScale:minScale];
[imageScrollView setZoomScale:minScale];
[imageScrollView setContentOffset:CGPointZero];
// clear memory
[imageView release];
imageView = nil;
[image release];
image = nil;
Here's the category method I've used to get UIImage using URL string:
+ (UIImage *)newImageWithContentsOfURL:(NSString *)imageURL {
NSURL *url = [[NSURL alloc] initWithString:imageURL];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
UIImage *image = [[UIImage alloc] initWithData:data];
[data release];
[url release];
return image;
}
Problem: The affect of loading a jpeg image of size 110 Kb (approx.) is that the real memory of the application jumps from 12 MB (approx.) to 38 MB (approx.). I was baffled when i first saw this. How is this possible? Uh, and the end result: Application crashes on iPhone 3G (occasionally).
Note that the memory readings were taken using Memory Monitor tool in Instruments - while testing the application on the device (not the simulator). Also note that Instruments show no memory leaks, and Static Analyzer doesn't point to anything suspicious either.
I need help!