Re: KVO can be unsafe in -init?
Re: KVO can be unsafe in -init?
- Subject: Re: KVO can be unsafe in -init?
- From: Graham Cox <email@hidden>
- Date: Wed, 9 Sep 2009 12:51:46 +1000
On 08/09/2009, at 12:36 AM, John Chang wrote:
Hi all,
Question: is it unsafe for some reason to be adding yourself as a KVO
observer during -init?
We have a singleton with an -init that looks something like this:
- (id)init
{
if ((self = [super init]))
{
_foo = [[NSMutableDictionary alloc] init];
_bar = [[NSMutableDictionary alloc] init];
[[XYZManager sharedManager] addObserver:self forKeyPath:@"allObjects"
options:NSKeyValueObservingOptionInitial context:NULL];
NSKeyValueObservingInitial will trigger an immediate send of the KVO
notification to self. Since you're still inside -init I wouldn't have
thought that was generally safe, though it may be in certain cases.
Sun Sep 6 13:41:26 unknown MyApp[1609] <Error>: *** Terminating app
due to
uncaught exception 'NSInvalidArgumentException', reason: '***
-[NSCFDictionary setObject:forKey:]: attempt to insert nil key'
So we're stumped as to why KVO is throwing an exception.
Because you're trying to use a nil key with a dictionary. Why not set
a breakpoint on objc_exception_throw and see where that is being
attempted?
The only theory is
that the NSKeyValueObservingOptionInitial option is causing KVO to do
something with self immediately
It is.
, but self isn't fully "set up" yet. Though
it's unclear why in this particular usage that would be unsafe
true, it's unclear. But debugging the exception should show you what's
happening.
--Graham
_______________________________________________
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