从两个阵列中删除重复的自定义对象并组合它们

时间:2014-12-01 12:48:29

标签: ios objective-c nsmutablearray nsarray nsmutableset

首先,我搜索了很多,但所有方法似乎都是基元或整个自定义对象。

我的情况是这样的。我在两个不同的数组中有一个类型自定义对象。但是,除了仅有2个字段外,每个对象的字段与另一个字段的字段完全不同。

我想要的是组合这两个数组,然后只删除那两个字段的重复。我怎么能这样做。我的代码到目前为止

NSMutableArray* testArray = [eventHandler returnAllEvents];
    NSMutableArray* combinedArray = [[NSMutableArray alloc]init];
    NSArray* finalArray = [[NSArray alloc]init];
    if (testArray.count==0) {
        for (int i = 0; i<facebookData.count; i++) {
            LSEvent* event = [facebookData objectAtIndex:i];
            [combinedArray addObject:event];
        }
        finalArray = [combinedArray arrayByAddingObjectsFromArray:calendarData];
    }
    NSMutableArray *uniqueArray = [NSMutableArray array];
    NSMutableSet *names = [NSMutableSet set];
    for (id obj in finalArray) {
        NSString *destinationName = [obj destinationname];
        if (![names containsObject:destinationName]) {
            [uniqueArray addObject:obj];
            [names addObject:destinationName];
        }
    }

2 个答案:

答案 0 :(得分:0)

如果要使用containsObject检查数组中是否存在该对象:您需要在自定义对象中实现 - (BOOL)isEqual:(id)other。

- (BOOL)isEqual:(id)other {
    if (other == self) {
      return YES;
    }
    if (!other || ![other isKindOfClass:[self class]]) {
      return NO;
    }
    if (self.identifier == other.identifier) {
      return NO;
    }
    return YES;
}

答案 1 :(得分:0)

你可以这样做

NSArray first = ...
NSMutableArray second = ... // this will be combine array

for (id someObj in first) {
   if ( [second filteredArrayUsingPredicate:[self predicateForObject:someObj ]].count == 0 ){
       [second addObject: someObj];
   }
}
相关问题