iOS中数组的排序方法

1函数介绍与实例  数组

函数一:- (void)sortUsingSelector:(SEL)comparator;函数

适用于数组中的元素自带比较函数时;对象

数组排序函数,调用该函数的对象为数组,comparator是调用该函数的数组中的元素的方法。函数参数类型为数组中的元素类型或者id类型,在调用时不须要传递参数,排序过程不可见,该函数执行时:循环取出各个元素,进行比较,而后放到合适的位置排序

使用实例:字符串

将数组中的元素按照字符串大小排序:it

NSMutableArray*array = [[NSMutableArray alloc] initWithObjects:@"White",@"Blue",@"Red",@"Black",nil];io

    [arraysortUsingSelector:@selector(compare:)];table

    NSLog(@"sorted array:%@",array);test

运行结果是:sorted array:扩展

(

                                                 Black,

                                                 Blue,

                                                 Red,

                                     White

)

   解释:在调用sortUsingSelector()方法时,咱们指定使用compare:方法来进行比较。它内部可能使用了类型来进行判断,由于比较的类型是NSString,因此会调用NSString 的compare:方法。排序的过程是不可见的,可是过程就是:取出各个元素,使用compare:比较,而后放到合适的位置。对于compare:函数则在NSString类的扩展(category)已经定义号了。系统已经知道如何断定A 字串和B字串谁比较大,对于本身定义好的类中,须要本身定义compare方法,并指定一个排序参数(好比咱们定义一个Sudent的类型,而后规定排序的时候按照ID来排。

 

函数二-(void)sortUsingFunction:(NSInteger (*)(id, id, void *))compare ontext:(void*)context;

数组中元素不带比较函数时,建议使用。

使用方法:只须要在调用比较函数的类中定义比较函数以下:

NSInteger sortObjectsByPatientID(id obj1, id obj2,void *context)

{

    NSString*d1 = [(Study*)obj1 patientID];//obj1 obj2 为数组中的元素,patientID是其属性之一

    NSString*d2 = [(Study*)obj2 patientID];

    return[d2 compare:d1];

}

而后调用比较函数:

            [listDataArraysortUsingFunction:sortObjectsByPatientName context:NULL];

 

函数三:- (void)sortUsingSelector:(SEL)comparator;函数。

利用该函数,须要在数组中的元素具备比较方法。

首先定义元素类,在其中实现比较方法:

类定义

@interface Study : NSObject

{

    NSString*patientID;

}

- (NSComparisonResult)compareID:(Study*)dic;

@end;

类实现

@implementation Study

- (NSComparisonResult)compareID:(Study*)dic

{

    return[patientID compare:dic.patientID];

}

@end;

在其余类中调用排序方法:

@interface Sorttest: NSObject<NSCopying,NSCoding>

{

   NSMutableArray *listArrray; //用来存储AddressCard对象的可变数组

}

-(void)sort

{

   [listArrray sortUsingSelector:@selector(compareID:)]; //sort方法,listArrray中存储着全部的Study类型对象                                                       //比较的方式就是调用compareID:的方法

}

相关文章
相关标签/搜索