Objective-C 對象按屬性排序 過濾

使用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 >"
)
*/

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章