NSMutableDictionary addition and removal KVO
Asked Answered
S

1

7

I have a quick question regarding KVO. I understand that for a NSArray if observing additions is desired you can do the following.

 NSIndexSet* set = [NSIndexSet indexSetWithIndex:[someIndex integerValue]];
            [self willChange:NSKeyValueChangeInsertion valuesAtIndexes:set forKey:@"theArrayName"];
                // add the objects at the specified indexes here
            [self didChange:NSKeyValueChangeInsertion valuesAtIndexes:set forKey:@"theArrayName"];

Upon registering for observation you will get a change dictionary with the indexes that changed.

However, I do not understand how I can observe new object additions to a NSMutableDictionary. Is there a way to observe object add/removal?

Thanks,

[EDIT] I found a solution which meets my current needs. I hope the following helps any future developers.

[self willChangeValueForKey:@"someDictionary" withSetMutation:NSKeyValueUnionSetMutation usingObjects:[NSSet setWithObject:someObject]];

[Images setObject:someObject forKey:someIndex];

[self didChangeValueForKey:@"someDictionary" withSetMutation:NSKeyValueUnionSetMutation usingObjects:[NSSet setWithObject:someObject]];
Surety answered 5/7, 2011 at 16:42 Comment(1)
+1 . Good Question / Answer. You should post the answer you have embedded in your question as an answer. You are currently on the "Unanswered" list. Posting an answer to your own question is actually encouraged on SO. Asking a question you already know the answer to and immediately after posting the answer is also encouraged (assuming the question is a good one that others may also encounter).Ciel
E
3

Just to make sure that question is answered. credit goes to @DoubleDunk

[self willChangeValueForKey:@"someDictionary" withSetMutation:NSKeyValueUnionSetMutation usingObjects:[NSSet setWithObject:someObject]];

    [Images setObject:someObject forKey:someIndex];

    [self didChangeValueForKey:@"someDictionary" withSetMutation:NSKeyValueUnionSetMutation usingObjects:[NSSet setWithObject:someObject]];
Emmuela answered 25/1, 2012 at 10:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.