views:

70

answers:

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.

+1  A: 

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
+1  A: 

You'll want to look at this

http://stackoverflow.com/questions/805547/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
}
Lou Franco
Thanks Lou, How would you suggest I get the companyId to identify the appropriate role from within the 'compare' method?
Benjamin Ortuzar
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
Updated answer with sortUsingFunction
Lou Franco
sortUsing function does exactly what I needed. Thanks Lou.
Benjamin Ortuzar