繁体   English   中英

如何比较两个字典

[英]How to compare two dictionary

我有两个字典,我想比较一下

实际上字典结构就像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;

任何人都可以建议任何有效的方法来做到这一点

现在我正在使用,但它并没有给我带来共同的利益,因为

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分钟

首先,您将数据存储在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]);

快乐编码!!!

假设您只需要比较“ 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];
    }
}

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

您可以享受很多好处:

  • 代码完成
  • 编译时检查
  • 自定义isEqual方法
  • 代码是不言自明的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM