数组的排序

TestSort.h 
Java代码   收藏代码
  1. #import <Foundation/Foundation.h>  
  2.   
  3.   
  4. @interface TestSort : NSObject {  
  5.     NSString *name;  
  6. }  
  7. @property (nonatomic,copy)NSString *name;  
  8. @end  


TestSort.m 
Java代码   收藏代码
  1. #import "TestSort.h"  
  2.   
  3. @implementation TestSort  
  4. @synthesize name;  
  5. @end  


NSInteger intSort(TestSort *num1,TestSort *num2, void *context)


{

return [num1.namecompare:num2.name];

}

// Implement loadView to create a view hierarchy programmatically, without using a nib.

- (void)loadView {

[superloadView];

TestSort *test1 = [[TestSortalloc] init];

TestSort *test2 = [[TestSortalloc] init];

TestSort *test3 = [[TestSortalloc] init];

TestSort *test4 = [[TestSortalloc] init];

TestSort *test5 = [[TestSortalloc] init];

TestSort *test6 = [[TestSortalloc] init];

test1.name =@"t4";

test2.name =@"t3";

test3.name =@"t2";

test4.name =@"t5";

test5.name =@"t6";

test6.name =@"t1";

//初始化数组

NSArray *array = [[NSArrayalloc] initWithObjects:test1,test2,test3,test4,test5,test6,nil];

for (TestSort *tempin array ) {

NSLog(@"test:%@",temp.name);

}

//第一种方法排序

NSArray *sortArray1 = [arraysortedArrayUsingFunction:intSortcontext:nil];

NSLog(@"-----------------sortArray1---------------------");

for (TestSort *tempin sortArray1 ) {

NSLog(@"sorttest:%@",temp.name);

}

//第二种方法排序

NSArray *sortArray2 =[arraysortedArrayUsingComparator:^(id TestSort1,id TestSort2){

TestSort *temp1 = (TestSort *)TestSort1;

TestSort *temp2 = (TestSort *)TestSort2;

NSComparisonResult result = [temp1.namecompare:temp2.name];

return result;

}];

NSLog(@"-----------------sortArray2---------------------");

for (TestSort *tempin sortArray2 ) {

NSLog(@"sorttest:%@",temp.name);

}

}





    //sortUsingDescriptors:适合元素是dict类型,initWithKey既是dict key.

    NSMutableArray *regions = [NSMutableArray array];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];

    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];

    [regions sortUsingDescriptors:sortDescriptors];

    [sortDescriptor release];





































评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值