Re: How to allocate and delegate; or how to keep GC and the static analyzer happy
Re: How to allocate and delegate; or how to keep GC and the static analyzer happy
- Subject: Re: How to allocate and delegate; or how to keep GC and the static analyzer happy
- From: Glen Low <email@hidden>
- Date: Sat, 10 Oct 2009 17:25:46 +0800
All
I have several cases of the following pattern in my code:
- (void)start
{
[[Something alloc] initWithDelegate:self];
}
- (void)finishWithSomething:(Something*)something
{
[something release];
}
The intent of course is that the Something object calls back the
caller with finishWithSomething: and that does the cleanup. Several
UI classes can work this way e.g. -[UIActionSheet
initWithTitle:delegate:...].
On 10/10/2009, at 12:29 PM, Jens Alfke wrote:
On Oct 8, 2009, at 7:33 PM, Glen Low wrote:
1. The code is not GC friendly as between the end of start and the
beginning of finishWithSomething, there are no references to the
object, so it may be collected.
There must be references to it; otherwise how would that object's
methods get called later on? Either it's a delegate of another
object (an NSURLConnection or NSTimer or whatever) or it starts a
new thread to run one of its methods. Either way, there are
references to the object that keep it alive.
Not necessarily. In a pathological but presumably legit case, whatever
happens in initDelegate: might only form a weak reference to the
Something object, thus the Something object would be subject to GC. Or
the thread etc. could somehow fail and never call finishWithSomething:
(thus leaking the Something object).
The main point is that I don't think I can rely on anything keeping a
reference to the newly allocated Something object.
2. The static analyzer in Xcode 3.2 doesn't like the construction,
thinking that the object is leaking from the start method.
I'm not sure what to do about that. Casting the result to (void)
might help, to explicitly state that you don't want to use the
result. (Does the static analyzer even work with GC? Stating that
the object is "leaking" only makes sense in a ref-counted
environment.)
I tried casting to void but the static analyzer wasn't swayed.
I suppose I can use the following pattern instead:
- (void)start
{
Something* something = [[Something alloc] initWithDelegate:self];
[_somethings addObject:something];
[something release];
}
- (void)finishWithSomething:(Something*)something
{
[_somethings removeObject:something];
}
... except for the overhead of keeping an array of _somethings around.
Cheers, Glen Low
---
pixelglow software | simply brilliant stuff
www.pixelglow.com
aim: pixglen
twitter: pixelglow
_______________________________________________
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