NSArrayController of NSManagedObject accesses *array* instead of *set*

| | August 4, 2015

A xib file in my OS X project contains a table view backed by an NSArrayController which is set to Entity Name (aka Core Data) mode. When I send an -add: message to this array controller, an exception is raised as the console emits:

NSManagedObjects of entity ‘Foo’ do not support -mutableArrayValueForKey: for the property ‘bar’.

Correct! Instead, NSManagedObjects support -mutableSetValueForKey:, and I’d always thought that NSArrayController knew this and behaved accordingly – being in Entity Name mode, I expect it to send -mutableSetValueForKey: to my Foo object, not -mutableArrayValueForKey:. From the documentation:

Typically the collection is an array, however, if the controller manages a relationship of a managed object (see NSManagedObject) the collection may be a set.

If I “fake it” by adding the following method to my Foo class, it prevents the exception from being raised but, of course, this doesn’t really work:

- (NSMutableArray*)mutableArrayValueForKey:(NSString*)key {
    [self willAccessValueForKey:key];

    NSMutableArray* result = [[[self valueForKey:key] allObjects] mutableCopy] ;

    [self didAccessValueForKey:key];
    return result;
}

What might be wrong here? I’ve checked the “mode” of that array controller five times.

Leave a Reply