iPhone and memory leaks: two watch-out tips

The time I spent believing that my buffered input stream class had a leak because of two silly mistakes somewhere else could have easily been better employed. So I am happy to share my findings and spare other developers the same frustration. No rocket science here, just two simple anti-patterns.

  1. when defining a property with the retain flag, you still have to release the corresponding instance variable when deallocating the containing object.
  2. when assigning a value to a retained property, make sure you are not retaining it yourself or – if you are – make sure you release it once assigned.

In a practical example, if you define a class like this one, where a property is implemented by retaining a value

@interface MyObject : NSObject {
OtherObject *value;
}

@property (nonatomic, retain) OtherObject * value;

@end

you will then need to release all the values in your -dealloc implementation, like so

@implementation MyObject

@synthesize reference;

- (void) dealloc {
[value release];
[super dealloc];
}

@end

And that covers point 1. As for point 2, here’s what you shouldn’t do (which is what I was originally doing!)

myObject. value = [[OtherObject alloc] init];

Because -alloc retains the object, and the property assignment retains the object, you’re leaking memory here, as you end up with a reference count of 2, but only one foreseeable -release call in the -dealloc method of MyObject. So the correct way of writing this kind of assign statement would be

OtherObject *obj = [[OtherObject alloc] init];
myObject. value = obj;
[obj release];

Leave a comment

Your email address will not be published. Required fields are marked *


*