如何将两个 NSDictionary 或 NSMutableDictionary 的 IntersectSet 与值相交?

How to IntersectSet of two NSDictionary or NSMutableDictionary with values?

想要合并两个 NSDictionaryNSMutableDictionary 仅具有 dict1 值。像 [NSMutableDictionary addEntriesFromDictionary:]intersectSet(来自 NSMutableSet)。

 Dict 1 = @{@”One”: @””, @”Two”: @”"}

 Dict 2 = @{@”One”: @”1”, @”Two”: 2, @”Three”: @”3"}

合并后我的期望输出= @{@”One”: @”1”, @”Two”: @”2”}

更新

我已经尝试过 [Dict1 addEntriesFromDictionary:Dict2] 这个给出答案 @{@”One”: @”1”, @”Two”: 2, @”Three”: @”3"}

我也试过 NSMutableSet

NSMutableSet *keysInA = [NSMutableSet setWithArray:tempDict.allKeys];
NSSet *keysInB = [NSSet setWithArray:tempDict1.allKeys];
[keysInA intersectSet:keysInB];
NSLog(@"keys in A that are not in B: %@", keysInA);

这个输出 One, Two, Three.

所以 [NSMutableSet setWithArray:][NSMutableDictionary addEntriesFromDictionary:] 不会给出我预期的结果。

如果上面的代码有任何作用,请让我明白。谢谢。

试试这个...

//Assuming both dictionaries have same kind of keys
NSMutableDictionary *dict1 = @{@"One" : @"", @"Two": @"", @"Three" : @""}.mutableCopy;
NSDictionary *dict2 = @{@"One" : @"1", @"Two": @"2", @"Three" : @"3",@"Four":@"4"};

for (NSString *key in dict1.allKeys)
{
    if (dict2[key])
    {
        dict1[key] = dict2[key];
    }
}
NSLog(@"Updated dict %@",dict1);
NSDictionary *dict1 = @{@"One": @"", @"Two": @"6"};

NSDictionary *dict2 = @{@"One": @"1", @"Two": @"2", @"Three": @"3"};

NSDictionary * dict = [dict2 dictionaryWithValuesForKeys:[dict1 allKeys]];

NSLog(@"dict %@",dict);

// Log value
dict {
One = 1;
Two = 2;
}

这是我所期望的。