ios开发 数组模型排序的集中方法

数组排序的API分为2中,一种是数组直接调用API排序,另一种根据NSSortDescriptor来排序

//数组中的排序Api

- (NSArray *)sortedArrayUsingComparator:(NSComparator NS_NOESCAPE)cmptr API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

- (NSArray *)sortedArrayWithOptions:(NSSortOptions)opts usingComparator:(NSComparator NS_NOESCAPE)cmptr API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

//NSSortDescriptor中的排序Api

这个类里面有很多排序的API,毕竟看类就知道,这是专门排序的类文件

+ (instancetype)sortDescriptorWithKey:(nullableNSString *)key ascending:(BOOL)ascending API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
  • (instancetype)sortDescriptorWithKey:(nullableNSString *)key ascending:(BOOL)ascending selector:(nullableSEL)selector API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
  • (void)viewDidLoad {

    [super viewDidLoad];

    NSMutableArray *dataArr = [NSMutableArray array];

    Person*person1 = [Personnew];

    person1.name=@"shanghai";

    person1.age=@"30";

    person1.height=1.88;

    [dataArraddObject:person1];

Person*person2 = [Personnew];

person2.name=@"shenzhen";

person2.age=@"26";

person2.height=1.79;

[dataArraddObject:person2];


Person*person3 = [Personnew];

person3.name=@"hangzhou";

person3.age=@"22";

person3.height=1.74;

[dataArraddObject:person3];

/*     ascending为YES是升序,反之为降序 ,    */

//升序

//推荐 “descriptorWithKey:ascending:”明显简单多了

NSArray *sortArr1 = [self sortByDataArr1:dataArr descriptorWithKey:@"height" ascending:YES];

NSArray*sortArr2 = [selfsortByDataArr2:dataArrascending:YES];

//降序

NSArray *sortArr3 = [self sortByDataArr1:dataArr descriptorWithKey:@"height" ascending:NO];

NSArray*sortArr4 = [selfsortByDataArr2:dataArrascending:NO];

NSLog(@"234");

}

/**

根据关键字排序,返回一个排序好的数组

@param dataArr 需要排序的数组

@param sortKey 排序关键字

@param ascending 降序 or 升序

@return 返回一个排序好的数组

*/

-(NSArray)sortByDataArr1:(NSArray)dataArr descriptorWithKey:(NSString*)sortKey ascending:(BOOL)ascending{

NSSortDescriptor *sortDescriptor1 = [NSSortDescriptor sortDescriptorWithKey:sortKey ascending:ascending];

NSArray*sortArr = [dataArrsortedArrayUsingDescriptors:@[sortDescriptor1]];

returnsortArr;

}

/**

根据你想要“升序还是降序”,返回一个排序好的数组

@param dataArr 需要排序的数组

@param ascending 升序还是降序

@return 返回一个排序好的数组

*/

-(NSArray)sortByDataArr2:(NSArray)dataArr ascending:(BOOL)ascending{

NSArray*sortArr = [dataArr  sortedArrayUsingComparator:^NSComparisonResult(Person * obj1, Person * obj2) {

    if(ascending) {

        if(obj1.height== obj2.height) {

            [obj1.namecompare:obj2.name];

        }

        if(obj1.height> obj2.height) {

            return NSOrderedDescending;

        }else{

            return NSOrderedAscending;

        }

    }else{

        if(obj1.height> obj2.height) {

            return NSOrderedAscending;

        }else{

            return NSOrderedDescending;

        }

        returnNSOrderedSame;

    }

}];

returnsortArr;

}

你可能感兴趣的:(ios开发 数组模型排序的集中方法)