iOS 对NSMutableArray进行排序和过滤的实例
程序员文章站
2023-12-19 11:54:34
根据实体类的属性进行排序,这个属性排序还可以增加几个排序规则,前后的规则先判断,如果一样的则根据第二个排序规则来判断
nssortdescriptor *sort...
根据实体类的属性进行排序,这个属性排序还可以增加几个排序规则,前后的规则先判断,如果一样的则根据第二个排序规则来判断
nssortdescriptor *sortdescriptor = [[nssortdescriptor alloc] initwithkey:@"data" ascending:yes];//其中,price为数组中的对象的属性,这个针对数组中存放对象比较更简洁方便 nsarray *sortdescriptors = [[nsarray alloc] initwithobjects:&sortdescriptor count:1]; [self.dataarray sortusingdescriptors:sortdescriptors];
过滤不会对原来的数据产生影响,而是生成符合过滤条件的nsarray数据
nspredicate *apredicate=[nspredicate predicatewithformat:@"id>=%ld and id<=%ld",3,5]; nsarray *newarr=[self.dataarray filteredarrayusingpredicate:apredicate];
下面是个例子可以运行看看
#import <foundation/foundation.h> @interface testbean : nsobject @property(nonatomic,assign)int id; @property(nonatomic,strong)nsstring* data; @end
#import <uikit/uikit.h> @interface viewcontroller : uiviewcontroller<uitableviewdelegate,uitableviewdatasource> @property (strong, nonatomic) nsarray *list; @end // // viewcontroller.m // first // // created by shanreal-ios on 17/10/16. // copyright © 2017年 shanreal.longzhenhao. all rights reserved. // #import "viewcontroller.h" #import "testbean.h" @interface viewcontroller () @property(nonatomic,strong)nsmutablearray* dataarray; @end @implementation viewcontroller - (void)viewdidload { [super viewdidload]; // do any additional setup after loading the view. _dataarray = [nsmutablearray array]; testbean* one = [[testbean alloc]init]; one.id = 1; one.data = @"one"; [_dataarray addobject:one]; one = [[testbean alloc]init]; one.id = 2; one.data = @"two"; [_dataarray addobject:one]; one = [[testbean alloc]init]; one.id = 22; one.data = @"two2"; [_dataarray addobject:one]; one = [[testbean alloc]init]; one.id = 3; one.data = @"three"; [_dataarray addobject:one]; one = [[testbean alloc]init]; one.id = 4; one.data = @"four"; [_dataarray addobject:one]; one = [[testbean alloc]init]; one.id = 44; one.data = @"four4"; [_dataarray addobject:one]; one = [[testbean alloc]init]; one.id = 5; one.data = @"five"; [_dataarray addobject:one]; one = [[testbean alloc]init]; one.id = 6; one.data = @"six"; [_dataarray addobject:one]; [self oneclick]; [self twoclick]; } -(void)oneclick{ nssortdescriptor *sortdescriptor = [[nssortdescriptor alloc] initwithkey:@"data" ascending:yes];//其中,price为数组中的对象的属性,这个针对数组中存放对象比较更简洁方便 nsarray *sortdescriptors = [[nsarray alloc] initwithobjects:&sortdescriptor count:1]; [self.dataarray sortusingdescriptors:sortdescriptors]; [self logarray:self.dataarray]; } -(void)twoclick{ nspredicate *apredicate=[nspredicate predicatewithformat:@"id>=%ld and id<=%ld",3,5]; nsarray *newarr=[self.dataarray filteredarrayusingpredicate:apredicate]; [self logarray:newarr]; } -(void)logarray:(nsarray*)array{ nslog(@"---------------------------------"); for(testbean* bean in array){ nslog(@"%d %@",bean.id,bean.data); } } @end
以上这篇ios 对nsmutablearray进行排序和过滤的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。