OBjective-C:在可变数组NSMutableArray中添加相同对象后,进行自定义的排序方式输出...

  以下为自定义的排序方式的实现

 1 #import "Person+Compare.h"
 2 
 3 @implementation Person (Compare)
 4 -(NSComparisonResult)CompareByName:(Person*)aPerson
 5 {
 6     return [self.name compare:aPerson.name];
 7 }
 8 -(NSComparisonResult)CompareByAge:(Person*)aPerson
 9 {
10     if(self.age > aPerson.age)
11         return NSOrderedDescending;
12     else if (self.age < aPerson.age)
13         return NSOrderedAscending;
14     else
15         return NSOrderedSame;
16 }
17 @end

  主函数测试:

  

#import <Foundation/Foundation.h>

#import "Person+Compare.h"

#import "Person.h"

int main(int argc, const char * argv[])

{

    @autoreleasepool

    {

        NSMutableArray *personArray = [[NSMutableArray alloc]initWithCapacity:20];

        [personArray addObject:[Person personWithName:@"Tom" andAge:20]];

        [personArray addObject:[Person personWithName:@"Smith" andAge:21]];

        [personArray addObject:[Person personWithName:@"Jhon" andAge:19]];

        [personArray addObject:[Person personWithName:@"Bruth" andAge:24]];

        

        //按姓名排序

        NSMutableArray *sortedByName = [NSMutableArray arrayWithArray:[personArray sortedArrayUsingSelector:@selector(CompareByName:)]];

        NSLog(@"%@",sortedByName);

        

        

        //按年龄排序

        NSMutableArray *sortedByAge = [NSMutableArray arrayWithArray:[personArray sortedArrayUsingSelector:@selector(CompareByAge:)]];

        NSLog(@"%@",sortedByAge);

         

    }

    return 0;

}

 

  测试结果为:

2015-08-18 18:03:26.997 可变数组的排序[2079:120917] (
    "name=Bruth,age=24",
    "name=Jhon,age=19",
    "name=Smith,age=21",
    "name=Tom,age=20"
)
2015-08-18 18:03:26.998 可变数组的排序[2079:120917] (
    "name=Jhon,age=19",
    "name=Tom,age=20",
    "name=Smith,age=21",
    "name=Bruth,age=24"
)
Program ended with exit code: 0

 

转载于:https://www.cnblogs.com/XYQ-208910/p/4740195.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值