从带有子对象的数组中获取唯一对象的算法?
我有一个数据类:
@interface Car : NSObject
{
Engine *_engine;
}
//...
使用类:
@interface Engine : NSObject
{
NSInteger _power;
NSString *_name;
}
//...
和一个数组:
NSArray *myArray = [ // a bunch of Car objects with Engines
如何创建一个包含基于引擎“功率”的所有唯一项目的新数组?
例如:
0 带发动机的汽车(功率 = 20,名称 =“发动机一”)
1 带发动机的汽车(功率 = 45,名称 =“发动机二”)
2 带发动机的汽车(功率 = 20,名称 =“发动机三”) )
最终数组将是汽车对象 0 和 1
两个数据类都有访问器,例如:
- (NSInteger)power;
I have a data class:
@interface Car : NSObject
{
Engine *_engine;
}
//...
With the class:
@interface Engine : NSObject
{
NSInteger _power;
NSString *_name;
}
//...
And an array:
NSArray *myArray = [ // a bunch of Car objects with Engines
How would I make a new array that contains all unique items based on Engine 'power'?
For Example:
0 Car with Engine ( power = 20, name = "engine one" )
1 Car with Engine ( power = 45, name = "engine two" )
2 Car with Engine ( power = 20, name = "engine three" )
Final array would be car objects 0 and 1
Both data classes have accessors, e.g:
- (NSInteger)power;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将根据发动机功率选择最后一个项目。
要获得第一个,请
将此行替换为:
Will pick the last item per engine power.
To get the first one replace the line
with this:
枚举数组,构建一个索引列表,这些索引的对象具有以前未见过的
power
值。创建一个集合来保存已经看到的
power
;-[NSArrayindexsOfObjectsPassingTest:]
处理构建索引列表。然后向原始数组询问其objectsAtIndexes:
。Enumerate the array, building up a list of indices whose objects have previously-unseen
power
values.Create a set to hold the already-seen
power
s;-[NSArray indexesOfObjectsPassingTest:]
handles building the index list. Then ask the original array for itsobjectsAtIndexes:
.