【问题标题】:Objective-C - How to compare arrays and extract the difference?Objective-C - 如何比较数组并提取差异?
【发布时间】:2009-10-30 11:07:03
【问题描述】:

可能重复:comparing-two-arrays

我有两个 NSArray,我想用第二个数组中的对象创建一个新数组,但不是 包含在第一个数组中。

Example:

NSMutableArray *firstArray = [NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil];
NSMutableArray *secondArray = [NSMutableArray arrayWithObjects:@"Bill", @"Paul", nil];

The resulting array should be: 

[@"Paul", nil];

我通过将对象与内部对象进行比较的双循环解决了这个问题。

有没有更好的解决方案?

【问题讨论】:

    标签: objective-c arrays


    【解决方案1】:
    [secondArray removeObjectsInArray:firstArray];
    

    这个想法来自another answer。

    【讨论】:

      【解决方案2】:

      如果重复项在数组中不显着,您可以使用NSMutableSet 的minusSet: 操作:

      NSMutableArray *firstArray = [NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil];
      NSMutableArray *secondArray = [NSMutableArray arrayWithObjects:@"Bill", @"Paul", nil];
      
      NSSet *firstSet = [NSSet setWithArray:firstArray];
      NSMutableSet *secondSet = [NSMutableSet setWithCapacity:[secondArray count]];
      [secondSet addObjectsFromArray:secondArray];
      
      [secondSet minusSet:firstSet]; // result is in `secondSet`
      

      【讨论】:

      • 这是不可能的。 Apple 的文档说 minusSet 是 void 类型。
      • 最后一条语句的正确代码是“[secondSet minusSet:firstSet];”它执行减法。不返回结果,而是对 secondSet 对象的操作。如果这是在子例程中,那么您将“返回 secondSet;”
      【解决方案3】:

      我想比较来自两个 NSArray 的图像。 一个数组,我是从核心数据库中获取的。其次,我有常量数组对象。

      我想知道Core数据库中是否存在第二个数组的对象。

      这是我使用的代码。

      // All object from core data and take into array.
      NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:@"student"];
      
      NSArray *dbresult = [[NSArray alloc]init];
      NSError *error;
      @try {
          dbresult = [context executeFetchRequest:fetchRequest error:&error];
      }
      @catch (NSException *exception) {
          NSString *logerror = [NSString stringWithFormat:@"error in fetching Rooms from coredata = %@",exception.description];
      NSLog(logerror)
      }
      @finally {
      }
      
      /*
       Get Unused images from list
       */
      
      NSMutableArray *usedImages = [dbresult valueForKey:@"roomImageLocalPath"];
      
      NSMutableSet *fSet = [NSMutableSet setWithArray:usedImages];
      NSMutableSet *sSet = [NSMutableSet setWithCapacity:[newImages count]];
      [sSet addObjectsFromArray:newImages];
      [sSet minusSet:fSet];
      
      NSArray *unusedImages = [secondSet allObjects];
      NSLog(@"unusedImages %@",unusedImages);
      

      【讨论】:

        猜你喜欢
        • 2017-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多