Why does autorelease work when release fails?
Why does autorelease work when release fails?
- Subject: Why does autorelease work when release fails?
- From: Tron Thomas <email@hidden>
- Date: Thu, 28 Jun 2007 20:49:27 -0700
I wrote some code similar to the following
NSLayoutManager* manager = [[self layoutManager:@"Some text"] retain];
…
float height = [layout defaultLineHeightForFont:font];
…
unsigned int glyphCount = [manager numberOfGlyphs];
…
[manager release];
I tried implementing the layoutManager function like this:
- (NSLayoutManager*)layoutManager:
(NSString*)text
{
NSTextStorage* storage = [[NSTextStorage alloc]
initWithString:text];
NSLayoutManager* manager = [[[NSLayoutManager alloc] init]
autorelease];
[manager setTextStorage:storage];
[storage release];
return manager;
}
This causes the call to [manager numberOfGlyphs] to crash the program.
I found that if I implemented layoutManager this way:
- (NSLayoutManager*)layoutManager:
(NSString*)text
{
NSTextStorage* storage =
[[[NSTextStorage alloc] initWithString:text] autorelease];
NSLayoutManager* manager = [[[NSLayoutManager alloc] init]
autorelease];
[manager setTextStorage:storage];
return manager;
}
I don't understand why the second verions works over the first
version. Since the storage is invoked with a call to alloc it should
be released. I would expect the call to [manager setTextStorage]
would create a reference to the storage so that the call to [storage
release] following would still allow the storage to remain valid.
What is the reason that the autorelease method works over the
explicit release method?
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden