0

我知道从 NSArray 中减去 NSArray 如果它是在此处找到的单个基本对象

但我拥有的是这样的对象

@interface Set : NSObject
@property (nonatomic, strong) NSString *ItemId;
@property (nonatomic, strong) NSString *time;
@property (nonatomic, strong) NSString *Category_id;
@property (nonatomic, strong) NSString *List_id;
@property (nonatomic, strong) NSString *name;
@end

如何从另一个具有相同对象的数组中删除具有集合对象的数组?它可以通过我知道的迭代来完成。还有其他方法吗?

编辑:为清楚起见

我有带有 5 个 Set 对象的数组 A ,我在数组 B中有 4 个 Set 对象, 数组 A 和数组 B 包含 3 个具有共同值的集合对象.. [注意:内存可能不同] 常见

我只需要一个数组 C =数组 A - 数组 B,它在结果数组 C 中有 2 个对象

谢谢你 :)

4

2 回答 2

3

您需要在类中实现- (NSUInteger)hashand- (BOOL)isEqual:(id)object方法Set

例如:-

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

- (BOOL)isEqual:(id)object
{
    return ([object isKindOfClass:[self class]] &&
            [[object ItemId] isEqual:_ItemId])

}

之后试试这个:

NSMutableSet *set1 = [NSMutableSet setWithArray:array1];
NSMutableSet *set2 = [NSMutableSet setWithArray:array2];
[set1 intersectSet:set2]; //this will give you only the obejcts that are in both sets

NSArray *commonItems = [set1 allObjects];

[mutableArray1 removeObjectsInArray:commonItems];//mutableArray1 is the mutable copy of array1

mutableArray1删除公共对象后,所有对象的顺序与之前相同。

于 2013-02-21T06:50:38.953 回答
1

通过使用NSSetNSPredicate我们可以满足您的要求。

Assessors *ass1 = [[Assessors alloc] init];
ass1.AssessorID = @"3";

Assessors *ass2 = [[Assessors alloc] init];
ass2.AssessorID = @"2";

Assessors *ass3 = [[Assessors alloc] init];
ass3.AssessorID = @"1";

Assessors *ass4 = [[Assessors alloc] init];
ass4.AssessorID = @"2";

NSSet *nsset1 = [NSSet setWithObjects:ass1, ass2,  nil];
NSSet *nsset2 = [NSSet setWithObjects:ass3, ass4, nil];

// retrieve the IDs of the objects in nsset2
NSSet *nsset2_ids = [nsset2 valueForKey:@"AssessorID"];

// only keep the objects of nsset1 whose 'id' are not in nsset2_ids
NSSet *nsset1_minus_nsset2 = [nsset1 filteredSetUsingPredicate:[NSPredicate predicateWithFormat:@"NOT AssessorID IN %@",nsset2_ids]];

for(Assessors *a in nsset1_minus_nsset2)
    NSLog(@"Unique ID : %@",a.AssessorID);

这里 Assessors 是我的 NSObject 类(在您的情况下设置),而 AssessorID 是该类的一个属性。

希望这能有所帮助。

于 2013-02-21T07:27:07.577 回答