You can use allValues
method to get all values as an NSArray
first. Then get a mutable copy of the array. Lastly, use any of the KVC methods you mentioned in your question on the mutable array (setValuesForKeysWithDictionary
, setValue:forKeyPath:
, etc...)
Based on your example
[[[myDict allValues] mutableCopy] setValuesForKeysWithDictionary:@{@"stringProp" : @"Same same!"}];`
[[[myDict allValues] mutableCopy] setValue:@"Another" forKeyPath:@"stringProp"];`
Or implement a category
@interface NSMutableDictionary (KVCForValues)
- (void)setValuesForValuesWithKeysWithDictionary:(NSDictionary<NSString *, id> *)keyedValues;
- (void)setValue:(nullable id)value forValuesWithKeyPath:(NSString *)keyPath;
@end
@implementation NSMutableDictionary (KVCForValues)
- (void)setValuesForValuesWithKeysWithDictionary:(NSDictionary<NSString *,id> *)keyedValues {
[[[self allValues] mutableCopy] setValuesForKeysWithDictionary:keyedValues];
}
- (void)setValue:(id)value forValuesWithKeyPath:(NSString *)keyPath {
[[[self allValues] mutableCopy] setValue:value forKeyPath:keyPath];
}
@end
And make use of it
[myDict setValuesForValuesWithKeysWithDictionary:@{@"stringProp" : @"Same same!"}];
[myDict setValue:@"Another" forValuesWithKeyPath:@"stringProp"];
This approach makes sense when you want to use KVC approach that is not possible with the accepted answer.
Concrete example
Assuming SomeClass
is defined as follows
@interface SomeClass: NSObject
@property (nonatomic, strong) NSString *someProperty;
@property (nonatomic, assign) NSInteger anotherProperty;
@end
@implementation SomeClass
- (NSString *)description {
return [NSString stringWithFormat:@"someProperty=%@, anotherProperty=%d", self.someProperty, (int)self.anotherProperty];
}
@end
Executing the following
SomeClass *value1 = [[SomeClass alloc] init];
value1.someProperty = @"aaa";
value1.anotherProperty = 111;
SomeClass *value2 = [[SomeClass alloc] init];
value2.someProperty = @"bbb";
value2.anotherProperty = 222;
SomeClass *value3 = [[SomeClass alloc] init];
value3.someProperty = @"ccc";
value3.anotherProperty = 333;
NSDictionary *someDictionary = @{@"key1": value1, @"key2": value2, @"key3": value3};
NSLog(@"%@", someDictionary);
Will produce the following output
key1 = "someProperty=aaa, anotherProperty=111";
key2 = "someProperty=bbb, anotherProperty=222";
key3 = "someProperty=ccc, anotherProperty=333";
After executing
[[[someDictionary allValues] mutableCopy] setValue:@"SameValue" forKeyPath:@"someProperty"];
NSLog(@"%@", someDictionary);
The output would be
key1 = "someProperty=SameValue, anotherProperty=111";
key2 = "someProperty=SameValue, anotherProperty=222";
key3 = "someProperty=SameValue, anotherProperty=333";