Re: Garbage Collection, Core Foundation, and the -finalize problem
Re: Garbage Collection, Core Foundation, and the -finalize problem
- Subject: Re: Garbage Collection, Core Foundation, and the -finalize problem
- From: Quincey Morris <email@hidden>
- Date: Mon, 16 Mar 2009 12:48:24 -0700
On Mar 16, 2009, at 11:08, Bill Cheeseman wrote:
I am looking for a strategy to avoid implementing a -finalize method
in a garbage-collected Objective-C class that declares a CFTypeRef-
style Core Foundation instance variable. I believe this is a fairly
common problem, because any Cocoa wrapper class for a Core
Foundation API would have to do it, but I haven't seen a usable
solution. Apple's GC documentation stops just short of suggesting an
answer.
In a reference counted environment, my class would simply implement
a -dealloc method that CFReleases the CFTypeRef ivar. I would use -
autorelease liberally in the usual fashion, and the CFTypeRef ivar
would get CFReleased automatically at the right time.
But in a garbage collected environment, according to the Garbage
Collection Programming Guide, I should do everything in my power to
avoid implementing a -finalize method. The Guide suggests that I
instead implement an -invalidate method to CFRelease the CFTypeRef
ivar, and then ensure that my -invalidate method is called whenever
I am finished with an instance of the class.
Assuming you do *not* call CFMakeCollectable or NSMakeCollectable,
it's perfectly OK to have a finalize method that calls CFRelease.
Because the CF instance variable lifetime is *not* GC-managed in that
case, there's no chance that GC will have collected the CF object in
advance. The dire warnings about finalize are based on the
indeterminate order of collection of *collectable* objects.
Michael Tsai's suggestion of making the CF object collectable, so that
it's collected automatically, and doing without the finalize method,
is another perfectly good approach. However, there are some non-CF
objects that can't be made collectable like this (e.g. CV...Ref). For
those, you would use the CFRelease-in-finalize technique.
_______________________________________________
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