What happens when the following code executes?
开发者_JAVA技巧Ball *ball = [[[[Ball alloc] init] autorelease] autorelease];
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.
Short answer: A crash ensues.
Once you have given object autorelease
call, now you have given its release responsibility to autorelease pool
, now it is just like you do not own it.. It will show random behavior it may crash or sometimes not.(Depends on when autorlease pool release it, if its release then it will crash)
精彩评论