Sawan Cool
Sawan Cool

Reputation: 158

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.

Upvotes: 2

Views: 349

Answers (4)

rob mayoff
rob mayoff

Reputation: 385920

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:.

Upvotes: 2

Janak Nirmal
Janak Nirmal

Reputation: 22726

Declare this at the top of the implementation file above @interface line

NSComparisonResult sortByName(id firstItem, id secondItem, void *context);

Following is the implementation for the method

NSComparisonResult sortByName(id item1, id item2, void *context)
{
    NSString *strItem1Name = [item1 name];
    NSString *strItem2Name = [item2 name];

    return [strItem1Name compare:strItem2Name]; //Ascending for strItem1Name you can reverse comparison for having descending result
}

This is how you would call it

[tempArray sortUsingFunction:sortByName context:@"Names"];

Upvotes: 2

Ilanchezhian
Ilanchezhian

Reputation: 17478

You can sort the array using NSArray's

- (NSArray *)sortedArrayUsingSelector:(SEL)comparator

method

For more detail, see this SO answer

Upvotes: 1

Sree
Sree

Reputation: 907

NSSortDescriptor *sortDes = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
        [tempArray_ sortUsingDescriptors:[NSArray arrayWithObject:sortDes]];
        [sortDes release];

Upvotes: 4

Related Questions