In several pieces of sample objective-c code I’ve seen people create new objects like this:
RootViewController *viewController = [[RootViewController alloc] init];
self.rootViewController = viewController; // self.rootViewController is a (nonatomic,retain) synthesized property
[viewController release];
[window addSubview: [self.rootViewController view]];
Is that any different “behind the scenes” than doing it like this instead?
self.rootViewController = [[RootViewController alloc] init];
[window addSubview: [self.rootViewController view]];
Edit: later I release rootViewController in my dealloc method:
-(void) dealloc {
[rootViewController release];
[super dealloc];
}
I’m just curious about the syntax between the two. One seems to create a temporary viewController object, and the other allocs/inits directly to self.rootViewController.
Seems a bit more straightforward/streamlined that way so I’m wondering why anyone would opt for the first method.
Thanks!
Answer:
So it looks like when using the second method it causes a memory leak because the rootViewController object would actually have a retain count of 2. (See my answer below with a link to a post that thoroughly explains it.) Thanks everyone!
Your second code snipppet doesn’t release the object you created.
self.rootViewController is a property that retains the object. So you’re creating an object using alloc, and then the setter method for self.rootViewController will retain it also. You should release all objects that you allocated. Always
What happens is:
When self is deallocated later on, the retained RootViewController object will be released, so its retain count becomes 1 again.
Result: you have a memory leak.