简体   繁体   中英

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.

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

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"];

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

You can sort the array using NSArray 's

- (NSArray *)sortedArrayUsingSelector:(SEL)comparator

method

For more detail, see this SO answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM