Search code examples
cocoansarraycontroller

NSArrayController reallocating array?


I have an NSCollectionView whose content is bound to an NSArrayController's arrangedObjects. When I call addObject: on the array controller, it seems to reallocate the underlying array - I can observe the pointer changing addresses. This isn't acceptable behavior for my particular case, as other objects also depend on the array.

Is this normal behavior or am I doing something wrong? I've seen some alternative solutions, such as directly modifying the array and calling willChangeValueforKey: and didChangeValueForKey: on the controller, but that doesn't seem like the most elegant solution.

I am fairly new to Objective-C and Cocoa, so go easy on me. :)

Thanks!


Solution

  • @interface NSArrayController : NSObjectController {
    @private
        void *_reserved4;
        id _rearrangementExtensions;
        NSMutableArray *_temporaryWorkObjects;
        NSUInteger _observedIndexHint;
        NSMutableIndexSet *_selectionIndexes;
        NSMutableArray *_objects;
        NSIndexSet *_cachedSelectedIndexes;
        NSArray *_cachedSelectedObjects;
        NSArray *_arrangedObjects;
    }
    

    If you look at NSArrayController's header, the instance variable for arrangedObject is a NSArray, so it will have to create a new array whenever you add a new object and is a normal behaviour.