使用NSMutavleArray 变长数组
建立一个Person对象,一个id属性和一个name属性,自定义了一个init方法,修改了description方法方便查看排序
//Person.h
@interface Person : NSObject
@property(nonatomic) unsigned int personId;
@property(nonatomic,weak) NSString *name;
- (instancetype)initWithPersonId:(int)personId andName:(NSString *)name;
@end
//Person.m
#import "Person.h"
@implementation Person
- (instancetype)initWithPersonId:(int)personId andName:(NSString *)name{
if (self = [super init]) {
self.name = name;
self.personId = personId;
}
return self;
}
- (NSString *)description{
return [NSString stringWithFormat:@"<id: %d name %@ >",_personId,_name];
}
@end
使用NSMutableArray中的sortUsingDescriptor方法 参数是一个NSSortDescriptor对象数组
NSSortDescriptor对象包含两个信息一个是数组对象中属性名,升序还是降序。NSSortDescriptor数组中的先后顺序即使排序优先级顺序。
过滤:使用NSPredicate 可以包含一条语句,其运算结果为真或假,例如“编号大于2“。NSMutableArray有filterUsingPredicate方法,剔除所有不能满足传入的NSPredicate对象的对象
filterdArrayUsingPredicate 可以创建一个新的数组,包含所有能够满足传入的NSPredicate对象的对象
//main.m
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
Person *person1 = [[Person alloc] initWithPersonId:2 andName:@"jack"];
Person *person2 = [[Person alloc] initWithPersonId:3 andName:@"aack"];
Person *person3 = [[Person alloc] initWithPersonId:4 andName:@"dack"];
Person *person4 = [[Person alloc] initWithPersonId:5 andName:@"yack"];
NSMutableArray *persons = [NSMutableArray array];
[persons addObject:person1];
[persons addObject:person2];
[persons addObject:person3];
[persons addObject:person4];
NSSortDescriptor *pi = [NSSortDescriptor sortDescriptorWithKey:@"personId" ascending:YES];
NSSortDescriptor *na = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
[persons sortUsingDescriptors:@[na,pi]];
NSLog(@"%@",persons);
[persons sortUsingDescriptors:@[pi,na]];
NSLog(@"%@",persons);
NSPredicate *pre = [NSPredicate predicateWithFormat:@"personId > 2"];
NSArray *numTwoPerson = [persons filteredArrayUsingPredicate:pre];
NSLog(@"%@",numTwoPerson);
}
return 0;
}
/*
2019-10-20 18:33:24.779684+0800 OC5[51608:7921931] (
"<id: 3 name aack >",
"<id: 4 name dack >",
"<id: 2 name jack >",
"<id: 5 name yack >"
)
2019-10-20 18:33:24.780359+0800 OC5[51608:7921931] (
"<id: 2 name jack >",
"<id: 3 name aack >",
"<id: 4 name dack >",
"<id: 5 name yack >"
)
2019-10-20 18:33:24.780534+0800 OC5[51608:7921931] (
"<id: 3 name aack >",
"<id: 4 name dack >",
"<id: 5 name yack >"
)
*/