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 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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [email protected]

Reply via email to