Search code examples
cocoakey-value-observing

Is this a good KVO-compliant way to model a mutable to-many relationship?


Say I'd like a mutable, unordered to-many relationship. For internal optimization reasons, it'd be best to store this in an NSMutableDictionary rather than an NSMutableSet. But I'd like to keep that implementation detail private.

I'd also like to provide some KVO-compliant accessors, so:

- (NSSet*)things;
- (NSUInteger)countOfThings;
- (void)addThings:(NSSet*)someThings;
- (void)removeThings:(NSSet*)someThings;

Now, it'd be convenient and less evil to provide accessors (private ones, of course, in my implementation file) for the dictionary as well, so:

@interface MYClassWithThings ()
@property (retain) NSMutableDictionary* keyedThings;
@end

This seems good to me! I can use accessors to mess with my keyedThings within the class, but other objects think they're dealing with a mutable, unordered (, unkeyed!) to-many relationship.

I'm concerned that several things I'm doing may be "evil" though, according to good style and Apple approval and whatnot. Have I done anything evil here? (For example, is it wrong not to provide setThings, since the things property is supposedly mutable?)


Solution

  • I wouldn't make a property (even a private one) for the dictionary, but I don't think there's anything wrong with it.

    … is it wrong not to provide setThings, since the things property is supposedly mutable?

    Yes. KVC will not like the absence of a setThings: method.