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

来源:互联网 发布:五金 用进销存软件 编辑:程序博客网 时间:2024/06/07 15:54
//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;}


0 0
原创粉丝点击