J W J W - 4 months ago 12
Objective-C Question

NSSortDescriptor on a property's property of an object

My class structure looks like this:

TargetDetail : NSObject
@property Target *target

Target : NSObject
@property NSUInteger location

I have an Array of TargetDetail objects. I want to sort them by the location. I tried this:

NSSortDescriptor *byNum = [[NSSortDescriptor alloc] initWithKey@"target.location" ascending:YES];
NSArray *sortDescriptorArray = [[NSArray alloc] initWithObjects:byNum, nil];

[targetArray sortedArrayUsingDescriptors:sortDescriptorArray];

My NSArray does not change. How do I use this method to sort? Thanks.


sortedArrayUsingDescriptors does not sort the specified array in place, it creates a new array, sorts that, and returns that. So your code needs to be:

 NSArray *mySortedArray = [targetArray sortedArrayUsingDescriptors:sortDescriptorArray];