1、这个方法可以实现数组的倒叙输出
reverseObjectEnumerator
NSArray *array = @[@"1",@"2",@"3",@"4"];
for (NSString *string in [array reverseObjectEnumerator]) {
NSLog(@"string ===== %@",string);
}
log日志:
2016-06-10 16:28:54.458 自定义搜索[4242:322108] string ===== 4
2016-06-10 16:28:54.459 自定义搜索[4242:322108] string ===== 3
2016-06-10 16:28:54.460 自定义搜索[4242:322108] string ===== 2
2016-06-10 16:28:54.461 自定义搜索[4242:322108] string ===== 1
2、这个方法也可以实现倒叙排列
[array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"obj ==== %@",obj);
}];
logo日志:
2016-06-10 16:35:59.281 自定义搜索[4295:326175] obj ==== 4
2016-06-10 16:36:07.952 自定义搜索[4295:326175] obj ==== 3
2016-06-10 16:36:15.771 自定义搜索[4295:326175] obj ==== 2
2016-06-10 16:36:20.927 自定义搜索[4295:326175] obj ==== 1
3、数组排序
NSArray *arr = [NSArray arrayWithObjects:@"23",@"34",@"54",@"0",@"ef", nil];
NSArray *sortArr = [arr sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"sortArr ==== %@",sortArr);
logo日志:
2016-06-10 17:07:36.509 自定义搜索[4526:344425] sortArr ==== (
0,
23,
34,
54,
ef
)
4、自定义排序
首先创建Person类
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
+ (Person*)personWithAge:(int)age withName:(NSString *)name;
- (NSComparisonResult)comparePerson:(Person *)person;
@end
在.m文件中实现这两个方法
+ (Person *)personWithAge:(int)age withName:(NSString *)name
{
Person *p = [[Person alloc] init];
p.name = name;
p.age = age;
return p;
}
#pragma mark 自定义排序
- (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;
}
然后在控制器中实现以下方法
Person *p1 = [Person personWithAge:24 withName:@"zhangshiye"];
Person *p2 = [Person personWithAge:22 withName:@"lisi"];
Person *p3 = [Person personWithAge:25 withName:@"wangwu"];
Person *p4 = [Person personWithAge:25 withName:@"liwu"];
Person *p5 = [Person personWithAge:21 withName:@"liwuxue"];
NSArray *arrays = [NSArray arrayWithObjects:p1,p2,p3,p4,p5, nil];
NSArray *sortedArray = [arrays sortedArrayUsingSelector:@selector(comparePerson:)];
NSLog(@"排序后:%@",sortedArray);
5.利用Block语法进行排序
// 利用Block语法进行排序
NSArray *dataArr = [NSArray arrayWithObjects:@"1bc",@"4b6",@"123",@"789",@"3ef",
nil];
NSArray *resultArr = [dataArr sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
NSComparisonResult result = [obj1 compare:obj2];
return result;
}];
NSLog(@"排序后:%@",resultArr);
logo日志:
2016-06-10 17:33:32.221 自定义搜索[5100:363766] 排序后:(
123,
1bc,
3ef,
4b6,
789
)