Wednesday, June 19, 2013

NSMutableDictionary removeObjectsForKeys example in Objective C (iOS).


NSMutableDictionary removeObjectsForKeys

Removes from the dictionary entries specified by elements in a given array.

- (void)removeObjectsForKeys:(NSArray *)keyArray

Parameters
keyArray
An array of objects specifying the keys to remove.

Discussion of [NSMutableDictionary removeObjectsForKeys]
If a key in keyArray does not exist, the entry is ignored.

NSMutableDictionary removeObjectsForKeys example.
NSMutableArray *keysToDelete = [NSMutableArray array];

for (id obj in [yourDictionary keyEnumerator]) {
    //do stuff with obj
    if (shouldBeDeleted(obj)) {
        [keysToDelete addObject:obj];
    }
}

[yourDictionary removeObjectsForKeys:keysToDelete];

Example of [NSMutableDictionary removeObjectsForKeys].
NSMutableDictionary* d = [NSMutableDictionary dictionaryWithDictionary: bigDict];
[d removeObjectsForKeys: [NSArray arrayWithObjects: @"address", @"age", nil]];

NSMutableDictionary removeObjectsForKeys example.
NSSet *keys = [lastMsgs keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) {
    return [obj[@"type"] intValue] == 1;
}];
NSMutableDictionary *dict = [lastMsgs mutableCopy];
[dict removeObjectsForKeys:[keys allObjects]];

End of NSMutableDictionary removeObjectsForKeys example article.