views:

31

answers:

1

I have an array of custom objects. One of the properties of these objects is an NSString. I want to sort by that property.

Because it is an NSString and not an NSNumber sorting is a little more difficult. Is there some kind of class method to help in this case? How should it be done?

+3  A: 

There is indeed. NSArray has a -sortedArrayUsingDescriptors: method. Call this, and pass an array of one sort descriptor for your property. For example, if your property is "lastName", then:

NSSortDescriptor  *desc = [[[NSSortDescriptor alloc] initWithKey: @"lastName" ascending: YES];
[array sortedArrayUsingDescriptors: [NSArray arrayWithObject: desc]];
Ben Gottlieb
That works for an array of NSStrings. I'm talking about an array of objects that have an NSString property.
awakeFromNib
@awakeFromNib: No, that works for an array of objects that have an NSString property called `lastName`. It will not work with an array of NSStrings, as they do not have a `lastName` property.
Chuck
I got it to work using sortUsingDescriptors instead. Did you make a mistake?
awakeFromNib
-sortUsingDescriptors will work on an NSMutableArray, I gave an example for a standard NSArray.
Ben Gottlieb