Cocoa in the Shell

colorWithPatternImage abusive memory usage

EDIT : Someone told me that this post was misleading, and it’s true.
To be clear, nothing wrong with colorWithPatternImage. As its name implies it should be used with small pattern images, the kind that are repeatable. You shouldn’t use it like in the following post in any case !

Today I just discovered something I was not aware of, as the title of the post suggests, it’s about the 2 UIColor’s methods colorWithPatternImage and initWithPatternImage. It turns out these two methods use a lot of memory, way more than we would expect.

I’m currently working on the iPad application of MacGeneration, and, as the development reaches its end, I started to do some performances analysis with Instruments, beginning with the Allocations tool.

It turned out that after the app was being launched, it was using much more memory that it was supposed to, in fact it was using 11.3Mb, which was just insane.

So I dug with Instruments and rapidly discovered that the culprit was colorWithPatternImage.
I was setting my viewController’s view backgroundColor like this (Both view and image dimensions were 1024x768) :

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background_test"]];

Try it yourself, just create a new View-based Application project, choose an image (here’s one), uncomment the viewDidLoad method and put the line above, launch Instruments and scream.

With the picture given in my link, when I launch the sample application with Instruments, it uses 7.32Mb.

To fix this insanity, I simply did this :

UIImageView* iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]];
iv.userInteractionEnabled = YES;
self.view = iv;
[iv release];[/code]

Launch it with Instruments again, and look at the difference, 1.32Mb, seems better no ?

Note that you have to specify userInteractionEnabled because it’s disabled by default on UIImageView.

So, in conclusion, try not to use these methods if you can, and to be honest you can, there’s always multiple ways to achieve what we want.