0

我做了以下方法来删除双打,但它并不完全有效。有什么建议么?

感谢您的帮助,

   -(NSMutableArray*)removeDuplicateCars:(NSMutableArray*)array{
    NSMutableArray *noDuplicates =[[NSMutableArray alloc]init];
    for (int i=0; i<[array count]; i++) {
        int counter =0;
        Car *car =(Car*)[array objectAtIndex:i];
        if ([noDuplicates count]==0) {
            [noDuplicates addObject:car];
        }
        for (int i=0; i<[noDuplicates count]; i++) {
            Car *car2 =(Car*)[array objectAtIndex:i];
            if (![car.name isEqualToString:car2.name]) {
                counter++;
            }
        }
        if (counter==[noDuplicates count]) {
            [noDuplicates addObject:car];
        }
    }
    NSLog(@"number of results = %i",[noDuplicates count]);
    return noDuplicates;
}
4

2 回答 2

1

创建一个名为“ addedCars”的数组 - 您将使用它来存储每辆独特汽车的名称。

在每次迭代中,使用 [NSArray containsObject:] 检查当前名称是否已添加到“addedCars”。如果没有,请将名称添加到“addedCars”,将汽车添加到“noDuplicates”。否则,跳过此项,因为它已添加到 noDuplicates。

于 2013-01-11T02:30:29.820 回答
0

确保[isEqual:]并按[hash]预期实施

-(NSMutableArray*)removeDuplicateCars:(NSMutableArray*)array{
    NSOrderedSet *set = [[NSOrderedSet alloc] initWithArray:array];
    NSMutableArray *newArr = [NSMutableArray arrayWithCapacity:[set count]];
    for (id obj in set) {
        [newArr addObject:obj];
    }
    return newArr;
}

您曾经![car.name isEqualToString:car2.name]比较对象,所以我相信您想过滤具有相同名称的对象?[isEqual:]比你需要覆盖Car

- (BOOL)isEqual:(id)other {
    if ([other isKindOfClass:[self class]]) {
        return [self.name isEuqalToString: [other name]];
    }
    return NO;
}

- (NSUInteger)hash {
    return [self.name hash];
}

还检查这个问题The best way to remove duplicate values from NSMutableArray in Objective-C?

于 2013-01-11T02:22:30.643 回答