如何比较两个字典

时间:2013-09-27 09:09:11

标签: iphone objective-c

我有两个字典数组,我想比较它们

实际上字典结构就像Facebook的兴趣列表,如下面的

我想找出我和朋友之间的共同利益

我检索了两个用户的兴趣列表,但我正在比较兴趣词典,因为created_time不同,所以我没有得到常用词典

        category = "Musical instrument";
        "created_time" = "2011-06-11T09:10:07+0000";
        id = 113099055370169;
        name = Guitar;

            category = "Musical instrument";
            "created_time" = "2013-09-27T06:02:28+0000";
            id = 113099055370169;
            name = Guitar;

任何人都可以提出任何有效的方法吗

现在我正在使用,但它没有给我共同的兴趣,因为created_time不同

for (int count = 0; count < [arrFriendsInterest count]; count++)
{
    NSDictionary *dictFriend = [arrFriendsInterest objectAtIndex:count];

    if ([arrMyIntrest containsObject:dictFriend]) {
        [arrMutualInterest addObject:dictFriend];
    }

}

其中arrFriendsInterest是包含朋友兴趣的词典数组

和arrMyIntrest是包含我兴趣的词典数组×评论只能编辑5分钟×评论只能编辑5分钟×评论只能编辑5分钟

3 个答案:

答案 0 :(得分:0)

首先,您将该数据存储在NSArray中吗?

如果是,那么请更容易使用以下代码。

// Do any additional setup after loading the view, typically from a nib.
NSArray *ar1 = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:@"Musical instrument",@"category",@"2011-06-11T09:10:07+0000",@"created_time",@"113099055370169",@"id", @"Guitar",@"name", nil], nil];


NSArray *ar2 = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:@"Musical instrument",@"category",@"2013-09-27T06:02:28+0000",@"created_time",@"113099055370169",@"id", @"Guitar",@"name", nil], nil];

NSMutableSet* set1 = [NSMutableSet setWithArray:ar1];
NSMutableSet* set2 = [NSMutableSet setWithArray:ar2];
[set1 unionSet:set2]; //this will give you only the obejcts that are in both sets

NSArray* result = [set1 allObjects];
NSLog(@"%@",[result mutableCopy]);

快乐编码。!!!

答案 1 :(得分:0)

这假设您只需要比较“id”值:

NSArray* myIds = [arrMyInterest valueForKey:@"id"];

for (int count = 0; count < [arrFriendsInterest count]; count++) {
    NSDictionary *dictFriend = [arrFriendsInterest objectAtIndex:count];

    // Not clear whether "id" is NSString or NSNumber -- use whichever
    NSString* friendId = [dictFriend valueForKey:@"id"];
    if ([myIds containsObject:friendId]) {
         [arrMutualInterest addObject:dictFriend];
    }
}

答案 2 :(得分:0)

而不是使用NSDictionary为什么不使用自定义类?

您可以获得很多好处:

  • 代码完成
  • 编译时检查
  • custom isEqual method
  • 代码是自我解释的