NSArrayController's add: swaps entire content array when array is accessed via keypath
NSArrayController's add: swaps entire content array when array is accessed via keypath
- Subject: NSArrayController's add: swaps entire content array when array is accessed via keypath
- From: Rick Hoge <email@hidden>
- Date: Thu, 25 Jun 2009 10:31:16 -0400
I recently tried a design where a certain object had an
NSMutableDictionary instance variable, which in turn contained an
NSMutableArray entry. After initializing this setup (in -init) as
shown here:
topLevelDictionary = [NSMutableDictionary dictionary]; // An
instance variable - I'm using GC
[topLevelDictionary setValue:[NSMutableArray array]
forKey:@"subArray"];
I then proceeded to add an NSTableView and NSArrayController to the
nib file, binding the controller's content array to the keypath
"topLevelDictionary.subArray"
I then set the controller's mode to 'Class' and set the flag to
prepare content, which was an NSMutableDictionary.
Next I added a button which was connected to the array controller's
add: method, and launched the app.
All worked fine, except that, when the new dictionaries are added by
clicking the add: button, the mutable array managed by the controller
is replaced with a new array (rather than inserting the new dictionary
in the original array). The new array has the correct content,
apparently having copied all the pre-existing dictionaries from the
old array.
This would be ok, except that I observe changes to
topLevelDictionary.subArray (see below) and need to perform special
processing on new items inserted in the subArray. This only works if
-observeValueForKeyPath:ofObject:change:context:
is called with a change type of NSKeyValueChangeInsertion, and I can
access the inserted items using
[change valueForKey:NSKeyValueChangeNewKey]
I confirmed that if subArray is promoted to an instance variable, then
add: will perform an insertion rather than creating a new array (in
fact I've used this a lot in the past). It seems that having the
array be part of a mutable compound object results in creation of a
new, copied array instead of an insertion.
There are a number of ways I can work around this, but I don't really
understand why this difference in behavior (array accessed as instance
variable vs. keypath inside compound object) is happening. Is this a
bug? or does it make sense in some way? This all would have been
really simple if it worked as expected...
Thanks for any insight anyone can provide,
Rick
_______________________________________________
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