本帖最后由 弥修斯 于 2015-8-20 18:41 编辑
简单排序(sortedArrayUsingSelector:)
代码如下:
- //简单排序
- void sortArray1(){
- NSArray *array = [NSArray arrayWithObjects:@"abc",@"456",@"123",@"789",@"ef", nil];
- NSArray *sortedArray = [array sortedArrayUsingSelector:@selector(compare:)];
- NSLog(@"排序后:%@",sortedArray);
- }
复制代码
这是字符串自带的compare:方法;
可以自己写compare:方法,进行对象的比较;如下:
- #import "Person.h"
- @implementation Person
- //直接实现静态方法,获取带有name和age的Person对象
- +(Person *)personWithAge:(int) age withName:(NSString *)name{
- Person *person = [[Person alloc] init];
- person.age = age;
- person.name = name;
- return person;
- }
-
- //自定义排序方法
- -(NSComparisonResult)comparePerson:(Person *)person{
- //默认按年龄排序
- NSComparisonResult result = [[NSNumber numberWithInt:person.age] compare:[NSNumber numberWithInt:self.age]];//注意:基本数据类型要进行数据转换
- //如果年龄一样,就按照名字排序
- if (result == NSOrderedSame) {
- result = [self.name compare:person.name];
- }
- return result;
- }
- @end
复制代码
主函数代码:
- void sortArray2(){
- Person *p1 = [Person personWithAge:23 withName:@"zhangsan"];
- Person *p2 = [Person personWithAge:21 withName:@"lisi"];
- Person *p3 = [Person personWithAge:24 withName:@"wangwu"];
- Person *p4 = [Person personWithAge:24 withName:@"liwu"];
- Person *p5 = [Person personWithAge:20 withName:@"liwu"];
- NSArray *array = [NSArray arrayWithObjects:p1,p2,p3,p4,p5, nil];
- NSArray *sortedArray = [array sortedArrayUsingSelector:@selector(comparePerson:)];
- NSLog(@"排序后:%@",sortedArray);
- }
复制代码
|
|