您可以先使用allValues 方法将所有值作为NSArray 获取。然后获取数组的可变副本。最后,在可变数组上使用您在问题中提到的任何 KVC 方法(setValuesForKeysWithDictionary、setValue:forKeyPath: 等...)
根据你的例子
[[[myDict allValues] mutableCopy] setValuesForKeysWithDictionary:@{@"stringProp" : @"Same same!"}];`
[[[myDict allValues] mutableCopy] setValue:@"Another" forKeyPath:@"stringProp"];`
或者实现一个类别
@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
并利用它
[myDict setValuesForValuesWithKeysWithDictionary:@{@"stringProp" : @"Same same!"}];
[myDict setValue:@"Another" forValuesWithKeyPath:@"stringProp"];
这种方法有意义,当您想使用 KVC 方法时,接受的答案是不可能的。
具体例子
假设SomeClass定义如下
@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
执行以下操作
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);
将产生以下输出
key1 = "someProperty=aaa, anotherProperty=111";
key2 = "someProperty=bbb, anotherProperty=222";
key3 = "someProperty=ccc, anotherProperty=333";
执行后
[[[someDictionary allValues] mutableCopy] setValue:@"SameValue" forKeyPath:@"someProperty"];
NSLog(@"%@", someDictionary);
输出将是
key1 = "someProperty=SameValue, anotherProperty=111";
key2 = "someProperty=SameValue, anotherProperty=222";
key3 = "someProperty=SameValue, anotherProperty=333";