【问题标题】:Subtract an array of complex objects from another array of same kind of objects ios从另一个相同类型的对象数组中减去一个复杂对象数组
【发布时间】:2013-02-21 06:28:15
【问题描述】:

我知道从 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

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

编辑:为清楚起见

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

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

谢谢你:)

【问题讨论】:

  • Remove duplicate objects from an NSMutableArray 并检查 micpringle 答案。
  • 检查它说它是关于通过循环比较和迭代来删除重复的......我知道那样。还有其他方法吗?
  • 让我明白...你有 2 个数组 arr1 和 arr2,它们都有 Set 的对象。你想找到resultArr=arr1-arr2。是吗?
  • 请将您的两个 NSArray 与 set 对象一起发布。
  • @Bhargavi :它只是 2 个带有 Set Objects 的 NSArray

标签: ios objective-c ipad nsarray


【解决方案1】:

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

例如:-

- (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 在删除公共对象后,所有对象的顺序与之前相同。

【讨论】:

    【解决方案2】:

    通过使用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 是该类的一个属性。

    希望这能有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-15
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 2022-08-13
      • 1970-01-01
      • 2023-02-03
      • 2013-02-21
      相关资源
      最近更新 更多