Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when the following code executes? Ball *ball = [[[[Ball alloc] init] autorelease] autorelease];

What happens when the following code executes?

Ball *ball = [[[[Ball alloc] init] autorelease] autorelease];
like image 712
rambabu459 Avatar asked Apr 19 '11 03:04

rambabu459


2 Answers

Let's break it down:

[Ball alloc]: This creates a Ball object that we own (and thus need to release).

[[Ball alloc] init]: This initializes the Ball object we just created.

[[[Ball alloc] init] autorelease]: This adds the Ball to the current autorelease pool, so it will be released when that pool is drained. This is the right thing to do if, for example, we were going to return the Ball from a method.

[[[[Ball alloc] init] autorelease] autorelease]: This autoreleases the Ball object again. This is 100% wrong. alloc is the only claim to ownership that we need to balance, so the Ball will now be released too many times. This could manifest in any number of ways, but it will probably just crash.

like image 181
Chuck Avatar answered Oct 18 '22 22:10

Chuck


Short answer: A crash ensues.

like image 27
Caleb Avatar answered Oct 18 '22 23:10

Caleb