簡體   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