从另一个相同类型的对象ios中减去一组复杂对象

时间:2013-02-21 06:28:16

标签: ios objective-c ipad nsarray

我知道如果NSArray是单个基本对象,则从NSArray中减去NSArray found here

但我拥有的是像这样的对象

@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

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

编辑:为清楚起见

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

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

谢谢你:)

2 个答案:

答案 0 :(得分:3)

您需要在- (NSUInteger)hash课程中实施- (BOOL)isEqual:(id)objectSet方法。

例如: -

- (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将使所有对象的顺序与之前的顺序相同。

答案 1 :(得分: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是该类的一个属性。

希望这可以提供帮助。

相关问题