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

Create an array called "addedCars" - you will use it to store the name of each unique car.

In each iteration, use [NSArray containsObject:] to check if the current name has already been added to "addedCars". If not, add the name to "addedCars" and the car to "noDuplicates". Otherwise, skip this item, as it has already been added to 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 に答える