Find objects with the same property value in NSMutableSet
Asked Answered
S

3

5

I have NSMutableSet of objects. All objects are unique obviously, but they might have same .angle value, which is NSInteger property.

I need to find out if there are two or more objects with the same .angle value and group then into an array.

How can i do that?
Any guidance would be much appreciated

Sevier answered 7/5, 2011 at 14:14 Comment(0)
A
12

Use an instance of NSPredicate to filter on the property you're interested in. For example:

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);
Aleph answered 7/5, 2011 at 14:59 Comment(0)
C
0

Might depend on how big your data set it. If large, you might have to sort by .angle and look for duplicates. 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.

Cns answered 7/5, 2011 at 14:44 Comment(0)
G
0

You can use sortUsingFunction:context: method of 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.

Globin answered 7/5, 2011 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.