Unexpectedly too much memory usage in drawRect: of UIView

My developing app for iPad often terminates abnormally … Not only the app stops but my device shows the APPLE mark.
The app was often showing memory warning, so I searched how much the app was using memory with Instruments. And I found that UIView object used unexpectedly large memory.
It said one UIView object used 24MB. I repeatedly added the objects to a main view. Therefore my app terminated abnormally?

I tested it with simple code.
    View4 *view = [[[View4 alloc] initWithFrame:self.view.bounds] autorelease];
    [self.view addSubview:view];
↑This makes an object of View4 which is a subclass of UIView, and adds to self.view in loadView method. Please don’t mind why ‘View4’, it’s just a number of my classes.

The View4 class draws a triangle in drawRect: method like this :
- (id)initWithFrame:(CGRect)frame
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    return self;

- (void)drawRect:(CGRect)rect
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, 0.3, 0.3, 0.3, 0.5);
    CGContextSetLineWidth(context, 0.5f);
    CGContextMoveToPoint(context, 10, 100);
    CGContextAddLineToPoint(context, 300, 100);
    CGContextAddLineToPoint(context, 160, 400);
    CGContextAddLineToPoint(context, 10, 100);

Instruments' result

Instruments says the memory usage is 12MB?

I also saw the usage in iPhone(4inch Retina) and the result was 2.78MB. This is because of the size of the screens? 1024*768 / 320*568 = 4.326…
12/2.78 = 4.316...
Well, it may be right.

I was surprised at the result which the large usage disappeared after deletion of drawRect: method.
- (void)drawRect:(CGRect)rect
↑But if you put the method with empty content, the usage gets 12MB. I can not understand…

Finally I changed to use CALayer. CALayer class has a method :
- (void)drawInContext:(CGContextRef)context
and this is also possible to draw lines or something, and the memory usage was just 3.00MB even in iPad. Good.
Develop | Comments(2) | Trackback(0)
No title

This information about drawRect: was very helpful to me. I had been tracking down memory usage for a long time and I was getting close to just giving up.

After reading your post, I cleaned many of my drawRect's (which were often doing nothing more than calling super) and my memory usage went down from 300MB to 50MB :>)

Re: No title
Thank you for your comment!!