IOS学习 NSMutableArray内部元素的排序

1函数介绍与实例   

函数一:

- (void)sortUsingSelector:(SEL)comparator;

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

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

使用实例:

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

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

    

    [array sortUsingSelector:@selector(compare:)];

    

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

运行结果是:

sorted array:(

    Black,

    Blue,

    Red,

    White

)

   解释:在调用sortUsingSelector()方法时,我们指定使用compare:方法来进行比较。它内部可能使用了类型来进行判断,因为比较的类型是NSString,所以会调用NSString 的compare:方法。排序的过程是不可见的,但是过程就是:取出各个元素,使用compare:比较,然后放到合适的位置。对于compare:函数则在NSString类的扩展(category)已经定义号了。系统已经知道如何判定A 字串和B字串谁比较大,对于自己定义好的类中,需要自己定义compare方法。

 

函数二

- (void)sortUsingFunction:(NSInteger (*)(id, id, void *))compare context:(void *)context;

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

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

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


{

    

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

    

    NSString*d2 = [(testView*)obj2 name];

    

    return [d2 compare:d1];

    

}

然后调用比较函数:

    testView *view1 = [[testView alloc]init];

    testView *view2 = [[testView alloc]init];

    testView *view3 = [[testView alloc]init];

    testView *view4 = [[testView alloc]init];

    NSMutableArray *listDataArray = [[NSMutableArray alloc]initWithObjects:view1,view2,view3,view4, nil];

    [listDataArray sortUsingFunction:sortObjectsByPatientID context:NULL]

 

函数三:

- (void)sortUsingSelector:(SEL)comparator;//与一是同一个函数,这里要讲的知识点不同

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

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

类定义

#import <UIKit/UIKit.h>


@interface testView : UIView

{

  

}

@property (nonatomic, SAFE_ARC_PROP_RETAIN) NSString *name;


- (NSInteger)compareName:(id)obj;


@end

类实现

#import "testView.h"


@implementation testView

- (NSInteger)compareName:(id)obj

{

    return [self.name compare:((testView *)obj).name];//这里参数obj就是一个要比较的对象

}

@end

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

[listDataArray sortedArrayUsingSelector:@selector(compareName:)];

// listDataArray中存储着所有的 testView类型对象                                              

//比较的方式就是调用compareName:的方法

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值