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];

As a general rule, in ObjC, C++, and Java it's a very bad idea to expose partially constructed objects to third parties, especially via global registries like KVO. In addition to the obvious problems, multi-threading and error handling are especially pernicious. The multi-threading issue is pretty self explanatory. The moment your uninitialized object is registered in KVO, others can invoke methods on it before you and your subclasses are done setting initial state.

The error handling issue involves what happens when an initializer needs to error out. In Cocoa, it should return nil, and if necessary, deallocate its previous self (to prevent +alloc from being unbalanced, and hence leak). But this now means that third parties can reach a deallocated object via these registrations. It will complicate how carefully you'll need to write your -dealloc method.

If the KVO registration is the last thing that happens, then it'll work, but of course, subclassing will break your assumptions. This falls under the hack category, and is not a pattern you want to replicate widely.

- Ben

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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 arch...@mail-archive.com

Reply via email to