// // main.m // NSArray的排序 // // Created by ganchaobo on 13-4-28. // Copyright (c) 2013年 ganchaobo. All rights reserved. // #import <Foundation/Foundation.h> #import "Student.h" #import "MyStudent.h" void SimpleNSArraySort(){ NSArray *arr=[NSArray arrayWithObjects:@"3",@"1",@"2", nil]; //NSArray中每个对象比较的时候,都是调用对象的compare进行比较 //用制定方法比较 NSArray *sortArray= [arr sortedArrayUsingSelector:@selector(compare:)]; NSLog(@"%@",arr); NSLog(@"======"); NSLog(@"%@",sortArray); } void ModelNArraySort(){ //数组里面要比较的对象,必须有一个方法返回compareRestult Student *s1=[Student StudentWithName:@"wen" AndLastName:@"li"]; Student *s2=[Student StudentWithName:@"xen" AndLastName:@"Li"]; Student *s3=[Student StudentWithName:@"xen" AndLastName:@"z"]; NSArray *arr=[NSArray arrayWithObjects:s1,s2,s3, nil]; NSArray *sortArry=[arr sortedArrayUsingSelector:@selector(CompareStudent:)];//每个对象的比较方法 NSLog(@"%@" ,sortArry); } void BlockNSArraySort(){ Student *s1=[Student StudentWithName:@"wen" AndLastName:@"li"]; Student *s2=[Student StudentWithName:@"xen" AndLastName:@"Li"]; Student *s3=[Student StudentWithName:@"xen" AndLastName:@"z"]; NSArray *arr=[NSArray arrayWithObjects:s1,s2,s3, nil]; //NSArray *sortArry=[arr sortedArrayUsingSelector:@selector(CompareStudent:)];//每个对象的比较方法 //用block <#^NSComparisonResult(id obj1, id obj2)cmptr#> NSArray *sortArry=[arr sortedArrayUsingComparator:^NSComparisonResult(Student *stu1 ,Student *stu2){ NSComparisonResult result=[stu1.LastName compare:stu2.LastName options:NSCaseInsensitiveSearch]; if(NSOrderedSame==result){ result=[stu1.Name compare:stu2.Name options:NSCaseInsensitiveSearch]; } return result; }]; NSLog(@"%@" ,sortArry); } void MoreModelNSArraySort(){ Student *s1=[Student StudentWithName:@"wen" AndLastName:@"li" AndBookName:@"Book1"]; Student *s2=[Student StudentWithName:@"xen" AndLastName:@"Li" AndBookName:@"Book1"]; Student *s3=[Student StudentWithName:@"xen" AndLastName:@"B" AndBookName:@"Book2"]; NSArray *arr=[NSArray arrayWithObjects:s1,s2,s3, nil]; NSSortDescriptor *BookDescript=[NSSortDescriptor sortDescriptorWithKey:@"bk.BookName" ascending:YES]; NSSortDescriptor *LastNameDescript=[NSSortDescriptor sortDescriptorWithKey:@"LastName" ascending:YES]; NSSortDescriptor *NameDescirpt=[NSSortDescriptor sortDescriptorWithKey:@"Name" ascending:YES]; NSArray *arr1=[NSArray arrayWithObjects:BookDescript,LastNameDescript,NameDescirpt, nil]; NSArray *sortArry=[arr sortedArrayUsingDescriptors:arr1];//调用对象的copare方法,没有指定block NSLog(@"%@",sortArry); } int main(int argc, const char * argv[]) { @autoreleasepool { //MoreModelNSArraySort(); MyStudent *mm=[MyStudent StudentWithName:@"aa" AndLastName:@"bb" AndBookName:@"cc" AndAge:12]; NSLog(@"%@",mm); } return 0; }