Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort an NSMutableArray with class objects in it?

I have a class Events

@interface MeEvents : NSObject {
    NSString* name;**strong text**
    NSString* location;

}

@property(nonatomic,retain)NSString* name;strong text
@property(nonatomic,retain)NSString* location;

In my NSMutablArray I add object of Events

Events* meEvent;
[tempArray addObject:meEvent];

Please tell me how to sort this array by member name.

like image 341
Sawan Cool Avatar asked Aug 28 '26 22:08

Sawan Cool


2 Answers

NSSortDescriptor *sortDes = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
        [tempArray_ sortUsingDescriptors:[NSArray arrayWithObject:sortDes]];
        [sortDes release];
like image 131
Sree Avatar answered Aug 31 '26 13:08

Sree


The easiest way is to use sortUsingComparator: like this:

[tempArray sortUsingComparator:^(id a, id b) {
    return [[a name] compare:[b name]];
}];

If you are sorting these strings because you want to show a sorted list to the user, you should localizedCompare: instead:

[tempArray sortUsingComparator:^(id a, id b) {
    return [[a name] localizedCompare:[b name]];
}];

Or you might want to use localizedCaseInsensitiveCompare:.

like image 29
rob mayoff Avatar answered Aug 31 '26 14:08

rob mayoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!