Re: Observing with GC
Re: Observing with GC
- Subject: Re: Observing with GC
- From: Quincey Morris <email@hidden>
- Date: Tue, 26 Feb 2008 00:01:04 -0800
On Feb 25, 2008, at 8:38 PM, Rob Keniger wrote:
On 26/02/2008, at 1:02 AM, glenn andreas wrote:
Note that in the non-GC world, you can't do that in -dealloc
(since the KVO "warning" about deallocating something that is
still be observed happens before the call to dealloc), so it's
unclear if there isn't some similar helpful warning before -
finalize is called...
Actually, I just checked this and you're right, calling -
removeObserver:forKeyPath: in a -finalize method triggers a
warning. You would need to do this elsewhere, although the
documentation is particularly scant as to exactly where.
I didn't get a warning in the finalize of an *observed* object. Here's
the code I used to test this (in a GC-only project):
@interface TestCase : NSObject {
NSString* name;
id observer;
}
@property (copy) NSString* name;
@property (assign) id observer;
@end
@implementation TestCase
- (void) finalize {
if (observer)
[self removeObserver: observer forKeyPath: @"name"];
[super finalize];
}
@synthesize name;
@synthesize observer;
- (void) setObserver: (id) newObserver {
if (observer)
[self removeObserver: observer forKeyPath: @"name"];
observer = newObserver;
if (observer)
[self addObserver: observer forKeyPath: @"name" options: 0
context: NULL];
}
@end
and in an instance of a different class:
TestCase* testCase = [[TestCase alloc] init];
testCase.observer = self;
testCase = nil;
[[NSGarbageCollector defaultCollector] collectExhaustively];
A breakpoint on the 'removeObserver' call in the finalize method
triggered, but there was no message logged.
On Feb 25, 2008, at 21:08, Bill Bumgarner wrote:
In general, -finalize should not be used to manage scarce resource
nor muck around with the app's object graph, including tearing down
observations and the like.
I find it hard to see anything dangerous in the finalize strategy used
in the above code, unless:
(a) there's a possibility that the observer is being finalized around
the same time, or
(b) the finalize method tries to set one of the observee's own
properties (thus triggering a notification to the observer, which
could perhaps zombify the observee if the observer stored its pointer)
In the application that triggered my original question, neither of
these conditions could possibly arise.
_______________________________________________
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