On Mar 8, 2012, at 07:39 , [email protected] wrote:
> Consider:
>
> - (void)finalize
> {
> // a single reference to _myIvar is held by self
> [[NSFileManager defaultManager] removeItemAtPath:_myIvar error:NULL]
> [super finalize];
> }
> I had initially assumed that _myIvar would be finalised after self.
> But the reality appears to be that an object and any objects referenced by
> ivars may be collected simultaneously.
> The crash therefore occurs when the ivar is finalised first and is
> subsequently re-assigned to a reference as a result of calling the
> NSFileManager method.
>
> Question:
> Is the above correct?
Yes, precisely so.
> If so it means that finalisers need to be very carefully about manipulating
> ivars.
Here's a good rule of thumb about referencing object ivars during finalize:
Don't.
In order to use object references safely in finalize, you have to be able to
prove that they're still alive, and that can be very, very hard -- at least
with ivars.
> In my case I could probably work around the issue by replacing
> -removeItemAtPath with unlink(2), assuming that I can get a char
> representation from my finalised NSString ivar.
In practical terms, finalize should limit itself to doing things with
non-objects, such as using 'free' on memory acquired by 'malloc'. You can never
safely get a char representation of your NSString during finalize. However, you
*could* have a malloc-ed char* ivar that you created earlier and use that to
delete the file.
> A more robust solution is a probably a separate -dispose method.
Yes, though knowing when to call it can be a puzzle in itself, if there are
multiple references to the object. In general, you'll probably need to invent a
reference counting mechanism to keep track of when it's OK for your dispose
method to actually dispose of things. That sounds ironic in a GC environment,
but there's nothing wrong with reference counting when you need to keep count.
:)
_______________________________________________
Cocoa-dev mailing list ([email protected])
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:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to [email protected]