2

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.

Jim Counts
  • 12,535
  • 9
  • 45
  • 63
Sawan Cool
  • 158
  • 3
  • 13

4 Answers4

4
NSSortDescriptor *sortDes = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
        [tempArray_ sortUsingDescriptors:[NSArray arrayWithObject:sortDes]];
        [sortDes release];
Sree
  • 907
  • 5
  • 14
  • This give SIGABRT error.Sir my array return class object like Then i receive object in Events* meEvent=[temparray objectAtIndex:i]; NSLog(@"Name %@",meEvent.eventname); – Sawan Cool Feb 23 '12 at 08:33
  • @SawanCool: You have to define the key in ["initWithKey:""].In the above code i just give an example as "name".Please init the sortDescriptor with your key. – Sree Feb 23 '12 at 08:39
2

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"];
Janak Nirmal
  • 22,706
  • 18
  • 63
  • 99
2

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

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
1

You can sort the array using NSArray's

- (NSArray *)sortedArrayUsingSelector:(SEL)comparator

method

For more detail, see this SO answer

Community
  • 1
  • 1
Ilanchezhian
  • 17,426
  • 1
  • 53
  • 55