2
votes

I am struggling in iOS (4) with allocating objects in one scope and releasing it in another scope. I am using properties as pointers to the objects. The object is allocated and initialized in one instance class method and I release it in the class’ dealloc method. The properties are declared with retain. Besides having problems with using properties likes this I also find it cumbersome to alloc and initialize the object and set the property.

NSObject *object = [[NSObject alloc] init];
Self.myProperty = object;
[object release];

I tried

self.myObject = [[NSObject alloc] init];

However that gave me a memory leak.

My question: Do I have to make this temporary object or is there a more elegant way of doing this?

A followup question: Do I have to both set the property to nil and release the autogenerated ivar?

[self setMyProperty:nil], [myProperty release];

When XCode 4 generates property stubs for you it puts [self setMyProperty:nil] in viewDidUnload and [_myProperty release] in dealloc.

2
assignment to nil is unnecessary.Dancreek
Meaning I should just release the ivars and forget about the properties? I don't mean to be hostile or anything; it’s only the way that Apple handles properties is a bit strange to me. Trying to figure out how to handle properties the iOS way.Kai Friis

2 Answers

2
votes

First question:

autorelease is your friend:

self.myObject = [[[NSObject alloc] init] autorelease];

Second question:

No, it's redundant, but harmless since the second operation will do nothing ([nil release] is safe). I'd advise using the self.XXX = nil; construct, as it's safer and very clear/readable.

1
votes

The self. notation is running through the synthesized setter which does a retain, which is why you need to do the autorelease on the init object. Conversely, you could leave off the self. and just use

myObject = [[NSObject alloc] init;

This line just sets the myObject pointer to the retained object, and you would not have any leak.

Here was my question from a while back along the same lines as yours:

MKReverseGeocoder autorelease/release question in Apple's CurrentAddress sample