---
title: "NSMutableArray 中排序"
author: "alex09"
date: "2011-07-24T14:02:18Z"
tags: []
categories: ["移动开发"]
slug: "nsmutablearray"
draft: false
lastmod: "2011-07-24T14:02:18Z"
id: 1131658
url: "https://alex09.iteye.com/blog/1131658"
---

使用sortedArrayUsingComparator方法


```java
NSArray *sorted = [_scores sortedarrayusingcomparator:^(id obj1, id obj2){
    if ([obj1 iskindofclass:[score class]] && [obj2 iskindofclass:[score class]]) {
        Score *s1 = (Score*)obj1;
        Score *s2 = (Score*)obj2;

        if (s1.points > s2.points) {
            return (NSComparisonResult)NSOrderedAscending;
        } else if (s1.points < s2.points) {
            return (NSComparisonResult)NSOrderedDescending;
        }
    }

    // TODO: default is the same?
    return (NSComparisonResult)NSOrderedSame;
}];
```


使用sortedArrayUsingSelector方法

```java
- (NSComparisonResult)compare:(Person *)otherObject {
    return [self.birthdate compare:otherobject.birthdate];
}

NSArray *sortedArray;
sortedArray = [drinkdetails sortedarrayusingselector:@selector(compare:)];
```


使用sortedArrayUsingDescriptors:sortDescriptors

```java
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[nssortdescriptor alloc] initWithKey:@"birthDate"
                                              ascending:YES] autorelease];
NSArray *sortDescriptors = [nsarray arraywithobject:sortdescriptor];
NSArray *sortedArray;
sortedArray = [drinkdetails sortedarrayusingdescriptors:sortdescriptors];
```