2

Im trying to find a good way to sort people by their Role within a specific company. What makes it tricky, is that a person can have one or more roles in different companies.

At the moment I have an array of 'Person' objects, and each of these objects has a NSSet of 'Roles' objects associated to it.

Similar to this:

Person
-personId
-personName (NSString)
-personRoles (NSSet)

Role
-roleId (NSNumber)
-roleWeight (NSNumber)
-roleName (NSString)
-companyId (NSNumber)

I need some code that is able to solve something similar to this:

Sort Array of Person by Role.roleWeight Where Role.companyId = X

I have been looking at the Sort Descriptors, but they dont seem to be enough to solve the challenge. Any suggestions are welcome.

Benjamin Ortuzar
  • 7,171
  • 6
  • 38
  • 46

2 Answers2

1

Assuming that you use NSArray to store data (on maybe CoreData store) you can use NSArrayController. Controller supports sort descriptors and NSPredicate as well. In your case you need a predicate to filter people (where role.companyId = x) and sort descriptors to sort by roleWeight.

Gobra
  • 4,243
  • 2
  • 12
  • 20
1

You'll want to look at this

How to sort an NSMutableArray with custom objects in it?

The basic idea is that given any two Person objects, you have to say how they compare. Is one less, greater, or are they the same.

- (NSComparisonResult)compare:(id)otherObject {
    // get the role for self
    // get the role for other object
    // compare their weights
    // return the right result
}

To pass in the company id, I think you'll need sortUsingFunction:context:, with a function like this

static int comparePersonsUsingCompanyID(id p1, id p2, void *context)
{
    // cast context to a company id
    // get the role for p1
    // get the role for p2
    // compare their weights
    // return the right result
}
Community
  • 1
  • 1
Lou Franco
  • 83,503
  • 14
  • 127
  • 183
  • Thanks Lou, How would you suggest I get the companyId to identify the appropriate role from within the 'compare' method? – Benjamin Ortuzar Jul 21 '10 at 19:15
  • That's a good point. There is a harder to understand variant of sort that takes a C function pointer and context. That one would allow you to pass in the company id. http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple%5Fref/doc/uid/20000138-BABCEEJD – Lou Franco Jul 21 '10 at 19:19
  • Updated answer with sortUsingFunction – Lou Franco Jul 21 '10 at 19:24
  • sortUsing function does exactly what I needed. Thanks Lou. – Benjamin Ortuzar Jul 21 '10 at 20:09