NSMutablearray搜索重复

时间:2014-09-05 09:15:25

标签: objective-c nsmutablearray

我有一个带有NSDictionary的数组 - 3个键3值,我需要搜索重复的对象并计算它们

  • 第一把钥匙 - 检查(1/0)
  • 第二个关键 - 重量(0 - 200)
  • 和第三个关键 - 方法(1 - 6)
  • 忽略 - 按键检查

代码:

NSMutableString *newtext = [[NSMutableString alloc] init];
NSMutableArray *original = [NSMutableArray arrayWithArray:[[_myExercise objectAtIndex:indexPath.row] objectForKey:@"myApproach"]];
NSMutableArray *myArr = [NSMutableArray arrayWithArray:[[_myExercise objectAtIndex:indexPath.row] objectForKey:@"myApproach"]];

for (int i = 0; i < [original count]; i ++) {
    int count = 0;
    for (int j = 0; j < [myArr count]; j ++) {
        if ([original containsObject:[myArr objectAtIndex:i]]) {
            count ++;
            NSLog(@"нашед %d", count);
            [original removeObjectAtIndex:0];
        }
    }

    NSLog(@"%@", original);

    NSString *myStr = [NSString stringWithFormat:@"%d Х %@ Х %@", count, [[myArr objectAtIndex:i] objectForKey:@"repeat"], [[myArr objectAtIndex:i] objectForKey:@"weight"] ];
    [newtext appendString:myStr];
}

2 个答案:

答案 0 :(得分:1)

在这里你可以做些什么,创建一个新的字典,其中包含重复的对象的密钥,以及重复的数量:

NSMutableDictionary * newDict = [NSMutableDictionary dictionaryWithCapacity:[originalDict count]];
for(id item in [originalDict allValues]){
    NSArray * keys = [originalDict allKeysForObject:item];
    if([keys count] > 1) {
      [newDict setObject:[NSNumber numberWithInteger:[keys count]] forKey:item];
    }
}

答案 1 :(得分:0)

如果我假设你想要的是myArr来包含没有重复的原始数组:

NSMutableString *newtext = [[NSMutableString alloc] init];
NSArray *original = _myExercise[indexPath.row][@"myApproach"];
NSMutableArray *myArr = [NSMutableArray array];

// iterate over the original
for (int i = 0; i < [original count]; i++) {
    int count = 0;
    // iterate over the rest of the original
    for (int j = i + 1; j < [original count]; j++) {
        // if these items are equal…
        if ([original[i] isEqualTo:original[j]]) {
            count++;    // bump the count
            NSLog(@"нашед %d", count);
        }
    }
    if (!count) {   // if there were no dups…
        [myArr addObject:original[i]];  // add the original item to myArr
    }
    NSLog(@"%@", original);
    NSString *myStr = [NSString stringWithFormat:@"%d Х %@ Х %@", count, myArr[i][@"repeat"], myArr[i][@"weight"]];
    [newtext appendString:myStr];
}