如何在iOS中具有相同值的NSMutableArray中合并2个NSDictionaries?

时间:2016-02-04 11:53:36

标签: ios objective-c nsmutablearray

我有一个带有NSDictionaries的NSMutableArray,如格式

(
            {
        "login_id" = 95;
        consDays = "Mon,Tue";
        consEndTime = 12600000;
        consStartTime = 9000000;
        duration = 10;
        id = 58;
        isActive = 1;
    },
            {
        "login_id" = 95;
        consDays = "Wed,Thur";
        consEndTime = 41400000;
        consStartTime = 23400000;
        duration = 10;
        id = 59;
        isActive = 1;
    },
            {
        "login_id" = 98;
        consDays = "Mon,Tue,Wed,Thur,Fri,Sat,Sun";
        consEndTime = 45000000;
        consStartTime = 9000000;
        duration = 30;
        id = 60;
        isActive = 1;
    },

我可以在这里看到前两个对象的“login_id”95是相同的,我需要合并内容并制作类似这样的东西

      {
        "login_id" = 95;
        consDays = "Mon,Tue-Wed,Thur";
        consEndTime = 12600000-41400000;
        consStartTime = 9000000-23400000;
        duration = 10;
        id = 58;
        isActive = 1;
    },

我试过for循环并且没有明白

for(int i=0;i<[[arr valueForKey:@"data"] count];i++){

    NSString *bloginId=[NSString stringWithFormat:@"%@",[[[arr valueForKey:@"data"] valueForKey:@"branchLogin_id"] objectAtIndex:i]];

    for(int j=0;j<[[arr valueForKey:@"data"] count];j++){

        NSString *firstId=[NSString stringWithFormat:@"%@",[[[arr valueForKey:@"data"] valueForKey:@"branchLogin_id"] objectAtIndex:i]];

        NSString *secondId=[NSString stringWithFormat:@"%@",[[[arr valueForKey:@"data"] valueForKey:@"branchLogin_id"] objectAtIndex:j]];
        NSLog(@"%@-%@",firstId,secondId);

        if([firstId isEqualToString:secondId]){
            NSLog(@"%@",[consultationDetailsArray valueForKey:@"branchLogin_id"]);
            if([[consultationDetailsArray valueForKey:@"branchLogin_id"]  containsObject:secondId]){

                NSString *str=[NSString stringWithFormat:@"%@,%@",[[consultationDetailsArray valueForKey:@"consDays"] objectAtIndex:j],[[[arr valueForKey:@"data"] valueForKey:@"consDays"] objectAtIndex:j]];
                NSLog(@"consDays %@",str);

            }else{

                [consultationDetailsArray addObject:[[arr valueForKey:@"data"] objectAtIndex:j]];
            }
        }
    }



}

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

讽刺的是,我现在正在做同样的事情。看起来最简单的方法是使用NSMutableDictionary。

    // Assume two starting dictionaries.
    dictionaryOne;
    dictionaryTwo;
    //
    // Create a mutable copy of the first
    NSMutableDictionary *merged = dictionaryOne.mutableCopy;
    [merged addEntriesFromDictionary: dictionaryTwo];
    //
    // merged now contains all keys of both dictionaries
    // keys that are in both dictionaries will have values
    // from dictionaryTwo.

希望这有帮助。