【Objective-C学习-11】NSArray的排序

//Student.h
#import <Foundation/Foundation.h>

@interface Student : NSObject

@property (nonatomic, retain) NSString *firstName;
@property (nonatomic, retain) NSString *lastName;

+ (id)studentWithFirstname:(NSString *)firstname Lastname:(NSString *)lastname;

- (NSComparisonResult)compareStudent:(Student *)stu;

@end


//Student.m
#import "Student.h"

@implementation Student

+ (id)studentWithFirstname:(NSString *)firstname Lastname:(NSString *)lastname {
    Student *stu = [[[Student alloc] init] autorelease];
    stu.firstName = firstname;
    stu.lastName = lastname;
    return stu;
}

- (NSComparisonResult)compareStudent:(Student *)stu {
    //先按姓排序
    NSComparisonResult result = [self.lastName compare:stu.lastName];
    
    //如果姓相同就按名排序
    if (result == NSOrderedSame)
        return [self.firstName compare:stu.firstName];
    
    return result;
}

- (void)dealloc {
    [_firstName release];
    [_lastName release];
    [super dealloc];
}

- (NSString *)description {
    return [NSString stringWithFormat:@"%@ %@", _lastName, _firstName];
}

@end

//main.m
#import <Foundation/Foundation.h>
#include "Student.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Student *stu1 = [Student studentWithFirstname:@"Dave" Lastname:@"Lin"];
        Student *stu2 = [Student studentWithFirstname:@"John" Lastname:@"Fang"];
        Student *stu3 = [Student studentWithFirstname:@"Tony" Lastname:@"Jia"];
        Student *stu4 = [Student studentWithFirstname:@"Ben" Lastname:@"Lau"];
    
        NSArray *array = [NSArray arrayWithObjects:stu1, stu2, stu3, stu4, nil];
        
        NSArray *array2 = [array sortedArrayUsingSelector:@selector(compareStudent:)];
        NSLog(@"%@", array2);
        
        
        NSArray *array3 = [array sortedArrayUsingComparator:^NSComparisonResult(Student *obj1, Student *obj2) {
            NSComparisonResult result = [obj1.lastName compare:obj2.lastName];
            if (result == NSOrderedSame)
                return [obj1.firstName compare:obj2.firstName];
            return result;
        }];
        NSLog(@"%@", array3);
        
        
        NSSortDescriptor *lastNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES];
        NSSortDescriptor *firstNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES];
        NSArray *desc = [NSArray arrayWithObjects:lastNameDesc, firstNameDesc, nil];
        NSArray *array4 = [array sortedArrayUsingDescriptors:desc];
        NSLog(@"%@", array4);
    
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值