Re: Dodgy Code - Low Level Memory Management Question!
Re: Dodgy Code - Low Level Memory Management Question!
- Subject: Re: Dodgy Code - Low Level Memory Management Question!
- From: Quincey Morris <email@hidden>
- Date: Tue, 26 Jan 2016 10:32:15 -0800
- Feedback-id: 167118m:167118agrif8a:167118smBO64LLMx:SMTPCORP
On Jan 26, 2016, at 06:00 , Dave <email@hidden> wrote:
>
> IOW, the autorelease will basically just be a NOP?
An autorelease is never a NOP. It’s a “release later”, not a “release if necessary”.
Rather than trying to count or balance retains globally, I think it’s easier to think in terms of ownership (+1 references) and non-ownership (+0 references). An init method must provide an owned (+1) reference to the object it returns. The cache, of course, must have a +1 reference to the cached object, too. So, rewriting your code to account for things already discussed, and simplifying your cache into a simple static variable, you get something like this:
> static id cachedObject;
>
> -(instancetype) initWithID:(NSString*) something
> {
> self = [super initWithSomething: something] // This ‘self’ is +1 according to init semantics
> if (self == nil)
> return nil;
>
> id myCachedObject = cachedObject; // A +0 local reference
>
> if (myCachedObject == nil)
> {
> cachedObject = [self retain]; // The cache needs its own +1 reference to keep the object alive until the cache is cleared
> return self; // ‘self’ is still +1 according to init semantics: this is unrelated to the retain in the previous line
> }
>
> else
> {
> [self autorelease]; // The “temporary” self is being discarded, so it needs to be released, eventually
> return [myCachedObject retain]; // Returning a +1 reference according to init semantics
> }
> }
(It been years since I’ve actually *written* any MRR code, so I apologize in advance for any stupid errors.)
If you do want to count retains, you’ll see that the object returned from this method, via either path, has a +2 retain count. That’s because +1 of that “belongs” to the caller, and you have no control over whether or when the caller does a corresponding release. The other +1 belongs to you, and is what keeps the cached object alive.
_______________________________________________
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