Re: A few questions about Memory Management
Re: A few questions about Memory Management
- Subject: Re: A few questions about Memory Management
- From: John Stiles <email@hidden>
- Date: Sat, 12 Feb 2005 09:59:59 -0800
On Feb 12, 2005, at 7:55 AM, Adrian R. Foltyn wrote:
Example code:
NSArray *allFileContents = [[NSArray arrayWithObject:[NSString stringWithContentsOfFile:@"/some/path"]] retain];
NSAutoreleasePool sends a release message to the NSString instance first thus setting the retain count to 0. Then the pool sends a release message to the NSArray instance and sets its retain count to 0. The array sends a release message to its member thus setting the retain count of the NSString instance to -1?
You counted wrong. Autorelease doesn't occur immediately—it occurs at some point in the future (unless you set things up differently, it happens when your code returns back to the AppKit event loop). Let me show you.
- an NSString is created with a retain count of
1. it is placed in the autorelease pool.
- an NSArray is created with a retain count of
1. it is placed in the autorelease pool.
- the NSString is added to the NSArray and it now has its retain count bumped to
2.
- the NSArray gets retained, bumping its retain count to
2 as well.
- at some point in the future, the autorelease pool does its magic. since both the NSString and NSArray are in the pool, both are released one time. since they're each at 2, this bumps them both down to a retain count of
1.
At no point does anything reach 0. Once something hits zero, it is immediately freed and becomes invalid.
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden