0

首先,我进行了很多搜索,但所有方法似乎都适用于原语或整个自定义对象。

我的情况是这样的。我在两个不同的数组中有一个类型自定义对象。但是,每个对象的字段都与另一个对象完全不同,只有 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];
        }
    }
4

2 回答 2

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;
}
于 2014-12-01T13:04:23.697 回答
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];
   }
}
于 2014-12-01T13:26:18.483 回答