具有子对象的数组中的唯一对象的算法?

时间:2011-11-15 00:00:31

标签: iphone objective-c ios nsmutablearray nsarray

我有一个数据类:

@interface Car : NSObject
{
  Engine *_engine;
}
//...

上课:

@interface Engine : NSObject
{
  NSInteger _power;
  NSString *_name;
}
//...

一个数组:

NSArray *myArray = [ // a bunch of Car objects with Engines

如何制作一个包含基于Engine'power'的所有独特项目的新数组?

例如:

0带引擎的车(功率= 20,名称=“引擎1”)

1辆带引擎的车(功率= 45,名称=“引擎2”)

2辆带引擎的车(功率= 20,名称=“引擎3”)

最终数组将是汽车对象0和1

两个数据类都有访问器,例如:

- (NSInteger)power;

2 个答案:

答案 0 :(得分:2)

NSArray *cars = ...;
NSMutableDictionary *carsByUniqueEnginePowers = [NSMutableDictionary dictionary];
for (Car *car in cars) {
    NSNumber *enginePower = [NSNumber numberWithInteger:car.engine.power];
    [carsByUniqueEnginePowers setObject:car forKey:enginePower];
}
NSArray *carsWithUniqueEnginePowers = [carsByUniqueEnginePowers allValues];

将根据发动机功率选择最后一项。

要获得第一个替换

[carsByUniqueEnginePowers setObject:car forKey:enginePower];

用这个:

if (![carsByUniqueEnginePowers objectForKey:power]) {
    [carsByUniqueEnginePowers setObject:car forKey:enginePower];
}

答案 1 :(得分:1)

枚举数组,构建一个索引列表,这些索引的对象以前没有看到power个值。

创建一个集合来保存已经看到的power; -[NSArray indexesOfObjectsPassingTest:]处理构建索引列表。然后询问原始数组objectsAtIndexes:

NSMutableSet * powerSet = [NSMutableSet set];
NSIndexSet * indexes;
indexes = [carArr indexesOfObjectsPassingTest:^BOOL(id car, NSUInteger idx, BOOL *stop) {
                  // valueForKey: will return an NSNumber instance for scalar values.        
                  NSNumber * powerNum = [[car engine] valueForKey:@"power"];
                  // This power is already in the set; pass over this car.
                  if( [powerSet containsObject:powerNum] ){
                      return NO;
                  }
                  // Add the new power to the set and include this car in the index set.        
                  else {
                      [powerSet addObject:powerNum];
                      return YES;
                  }
              }];
NSArray * uniqueEnginePowerCars = [carArr objectsAtIndexes:indexes];