简体   繁体   English

如何使用类对象对NSMutableArray进行排序?

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

I have a class Events 我有课程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 在我的NSMutablArray中,我添加了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 在@interface行上方的实现文件的顶部声明它

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: 最简单的方法是使用sortUsingComparator:像这样:

[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: 如果要对这些字符串进行排序,因为要向用户显示已排序的列表,则应该localizedCompare:而不是:

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

Or you might want to use localizedCaseInsensitiveCompare: . 或者您可能想使用localizedCaseInsensitiveCompare: .

You can sort the array using NSArray 's 您可以使用NSArray对数组进行排序

- (NSArray *)sortedArrayUsingSelector:(SEL)comparator

method 方法

For more detail, see this SO answer 有关更多详细信息,请参阅 SO答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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