Reputation: 16452
I've a model object that extends from NSObject called column. Column has two fields, properties and data. Properties is an NSDictionary that stores arbitrary key/value pairs while data is an array.
Columns come in arrays and I need to sort them by a value I know will always be in properties, a value with the key ordinal_position.
I'm using the following code to sort but it always fails because there is no "ordinal_position" in the model object, only in the properties of the model object:
NSArray *unsortedArray = [resultStore allValues];
NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"ordinal_position" ascending:YES] autorelease];
NSArray *sortedArray = [unsortedArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
How can I tell NSSortDescriptor to look for the property in a dictionary in the model object?
Upvotes: 0
Views: 429
Reputation: 60140
You should define your own selector that returns an NSComparisonResult and implement it:
- (NSComparisonResult)compareByProperty:(Column *)aColumn {
id thisValue = [self valueForKey:@"ordinal_position"];
id otherValue = [self valueForKey:@"ordinal_position"];
return [thisValue compare:otherValue]; // Replace to suit your logic
}
Then use the NSArray method sortedArrayUsingSelector:
:
NSArray *sortedArray = [unsortedArray sortedArrayUsingSelector:@selector(compareByProperty:)];
Note that your comparison method must exist on your model object, not on the class you're calling this from - the idiom is that you're comparing some given model object (self
) to another model object (aColumn
) from within the first object.
Upvotes: 2