- #import <Foundation/Foundation.h>
- @interface TestSort : NSObject {
- NSString *name;
- }
- @property (nonatomic,copy)NSString *name;
- @end
TestSort.m
- #import "TestSort.h"
- @implementation TestSort
- @synthesize name;
- @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];