• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: KVO can be unsafe in -init?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: KVO can be unsafe in -init?


  • Subject: Re: KVO can be unsafe in -init?
  • From: Ben Trumbull <email@hidden>
  • Date: Wed, 9 Sep 2009 01:14:08 -0700

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 (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


  • Prev by Date: Re: how to use Tx3gDescriptionHandle
  • Next by Date: Re: NSController's class accessing NSDocument methods
  • Previous by thread: Re: KVO can be unsafe in -init?
  • Next by thread: Re: KVO can be unsafe in -init?
  • Index(es):
    • Date
    • Thread