Cyprian
Cyprian

Reputation: 9453

Observing insertions and removals from NSMutableSet using observeValueForKeyPath

I would like to be notified about a new insertion in the NSMutableSet and thus this is what I am doing, but for some reason it is not calling observeValueForKeyPath method

Just for test:

-(void)observ{
    [self addObserver:self forKeyPath:@"connections" options:NSKeyValueChangeInsertion context:NULL];

    [connections addObject:@"connectionName"];

}

This is never called:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{

    if( [keyPath isEqualToString:@"connections"] ) {

        NSLog(@"added new object");
    }
}

Is NSMutablSet KVC ?

Upvotes: 4

Views: 1098

Answers (1)

Sean
Sean

Reputation: 5820

NSMutableSet is indeed KVO/KVC compliant. However, in order to receive the notifications with the way you have this set up, you need to implement the KVC accessor methods for a set. Information can be found here. Essentially, you have to implement methods called:

-countOfConnections
-enumeratorOfConnections
-memberOfConnections:
-addConnectionsObject:
-removeConnectionsObject:
-intersectConnections:

You must use these methods to access and mutate your set in order to receive KVO notifications.

Finally, in your -observeValueForKeyPath method, you can use the value of the key kind in the change dictionary to determine what type of mutation occurred (addition, deletion, etc.). The values can be found here and are listed under "NSKeyValueChange". Hope this helps.

Upvotes: 3

Related Questions