Search code examples
objective-ccocoansmutabledictionarykvc

Set the same value for all existing keys in an NSDictionary


In KVC, I usually use setValues:forKeyPath: to set the same value for objects in a collection. E.g.:

NSMutableArray <SomeClass *> *arr = [[NSMutableArray alloc] initWithCapacity:10];
for (int i = 0; i < 10; i++) {
    SomeClass *obj = [[SomeClass alloc] init];
    obj.stringProp = @(i).stringValue;
    [arr addObject:obj];
}

NSLog(@"- %@", [arr valueForKeyPath:@"stringProp"]);
[arr setValuesForKeysWithDictionary:@{@"stringProp" : @"Same same!"}];

NSLog(@"- %@", [arr valueForKeyPath:@"stringProp"]);
[arr setValue:@"Another" forKeyPath:@"stringProp"];

NSLog(@"- %@", [arr valueForKeyPath:@"stringProp"])

But, for a dictionary, can we use that as well? Now I've gotta set values manually:

NSMutableDictionary *myDict;
//... setupValues
NSString *valueToSet = @"Hehe";
for (NSString *key in myDict) {
    [myDict setObject:valueToSet forKey:key];
}

Is there a simple solution for a dictionary, like the example above?


Solution

  • I'm not sure if there is a function for that (I guess it don't), but in case you gonna need to do that multiple times, you can add a function to NSMutableDictionary to help you with that:

    @interface NSMutableDictionary (NSMutableDictionarySetAllKeysObject)
    -(void)setAllKeysObject:(nonnull id)object;
    @end
    
    @implementation NSMutableDictionary (NSMutableDictionarySetAllKeysObject)
    -(void)setAllKeysObject:(nonnull id)object
    {
        for (NSString *key in self.allKeys) {
            [self setObject:object forKey:key];
        }
    }
    @end
    

    So you would be able to do that:

    NSString *valueToSet = @"Hehe";
    [myDict setAllKeysObject:valueToSet];