您可以使用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";
可能是他們不具備一個功能(沒有?)。我會在幾天後接受你的回答,以防某人找到了我要求的方式:p – Eddie