我制作了以下方法来删除双打,但它并没有完全奏效。有什么建议吗?
感谢您的帮助,
-(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;
}
答案 0 :(得分:1)
创建一个名为“addedCars”的数组 - 您将使用它来存储每辆独特汽车的名称。
在每次迭代中,使用[NSArray containsObject:]检查当前名称是否已添加到“addedCars”。如果没有,请将名称添加到“addedCars”,将汽车添加到“noDuplicates”。否则,请跳过此项,因为它已添加到noDuplicates。
答案 1 :(得分: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?