Subtle difference of add: and insert: in an NSArrayController
Young Cocoa programmers learning bindings will inevitably play around with NSArrayController. Tutorials will have them build a simple app to demonstrate the controller, creating a button that says “New Person” and then connect that button to the controller using the add: action. Curious programmers may notice the insert: method and wonder what is the difference and look toward the API docs:
add:
Creates and adds a new object to the receiver’s content and arranged objects.insert:
Creates a new object and inserts it into the receiver’s content array.
Well that clears everything up. </sarcasm>.
If you look harder you may find this nugget in the Cocoa Bindings Programming Topics:
With an array controller
add:creates a new object using the controller’s newObject method and appends it to the controller’s content collection. Theremove:method removes the currently selected objects in the array controller from the collection. Theinsert:method creates a new object using the controller’s newObject method, and inserts it after the current selection.
In a perfect world we would take that answer and be happy but sadly a small practice application later we find out the real truth…
Sample Application Using add: and insert:
insert: happens before the current selection not after the current selection as the documentation would have us believe.
In my eyes this is a bug and as such I’ll file it in radar. rdar://6546023 The conceptual documentation needs to be fixed, and preferably the description for insert: in the API docs broadened as well.
PS: Upon re-reading the API docs it would also suggest using insert: doesn’t add the new object to the arrangedObjects collection. The add: descrition specifically says it adds the new object to arrangedObjects and because insert: does not say that, the implication is insert: does not (eventhough it does to my simple understand of things).
Posted on: January 31, 2009 – 7:29 AM

2 Comments
“Young Cocoa programmers learning bindings will enviably play around with NSArrayController.”
“enviably” is derived from “envy” (a feeling of longing for someone else’s possessions, qualities or luck). I think you mean: “inevitably” (certain to happen).
Also, there is this:
“Well that clears everything up. < /sarcasem >.”
You are missing an opening “< sarcasem >” which should actually be spelled “< sarcasm >”. (Note: extra spaces were added to defeat the comment system formatting).
Thanks for the corrections WTF. :)
Post a Comment | Comment RSS feed