简体   繁体   English

在NSMutableSet中查找具有相同属性值的对象

[英]Find objects with the same property value in NSMutableSet

I have NSMutableSet of objects. 我有NSMutableSet对象。 All objects are unique obviously, but they might have same .angle value, which is NSInteger property. 所有对象显然都是唯一的,但它们可能具有相同的.angle值,即NSInteger属性。

I need to find out if there are two or more objects with the same .angle value and group then into an array. 我需要找出是否有两个或更多具有相同.angle值和组的对象然后进入一个数组。

How can i do that? 我怎样才能做到这一点?
Any guidance would be much appreciated 任何指导都将非常感谢

Use an instance of NSPredicate to filter on the property you're interested in. For example: 使用NSPredicate实例过滤您感兴趣的属性。例如:

NSSet *dogs = [NSSet setWithObjects:
                [Dog dogWithName:@"Fido" age:2],
                [Dog dogWithName:@"Fluffy" age: 3],
                [Dog dogWithName:@"Spot" age:2],
                nil];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age == %d", 2];
NSSet *twoYearOldDogs = [dogs filteredSetUsingPredicate:predicate];

NSLog(@"%@", twoYearOldDogs);

Might depend on how big your data set it. 可能取决于您的数据设置的大小。 If large, you might have to sort by .angle and look for duplicates. 如果大,您可能必须按.angle排序并查找重复项。 Simple way is just to create a copy of data set, iterate it, for item N, look at N+1 to the end for all with same .angle and if found, remove them from this copy set and add to output set. 简单的方法就是创建数据集的副本,迭代它,对于项目N,查看N + 1到所有具有相同.angle的结尾,如果找到,则从这个副本集中删除它们并添加到输出集。

You can use sortUsingFunction:context: method of NSMutableArray. 您可以使用sortUsingFunction:context:NSMutableArray的方法。 (Though it is for sorting you can get your task done with better efficiency). (虽然它用于排序,但您可以更高效地完成任务)。

  NSComparisonResult compare(YourClass *firstObject, YourClass *secondObject, void *context) {
  if ([firstObject angle] < [secondObject angle])
    return NSOrderedAscending;
  else if ([firstObject angle] > [secondObject angle])
    return NSOrderedDescending;
  else 
  {
    //Normally here NSOrderedSame is returned. 
    //Put your logic stuff here.i.e. storing object for having common angle.
  }
}

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM