我们在平常开发编写代码的时候,都习惯啦使用for循环来遍历集合。今天我来分享一下用别的写法遍历集合。下面以数组为例。
NSArray *arrayabc = @[@"1",@"2",@"3",@"4",@"5"];
普遍的遍历写法
for(inti=0; i<arrayabc.count; i++){
NSLog(@"%@",arrayabc[i]);
}
for(id str in arrayabc) {
NSLog(@"%@",str);
}
for(NSString*str in arrayabc) {
NSLog(@"%@",str);
}
利用块的遍历方法:
(1)正常的顺序块遍历写法
[arrayabc enumerateObjectsUsingBlock:^(id _Nonnullobj,NSUIntegeridx,BOOL*_Nonnullstop) {
NSLog(@"%@",obj);
}];
打印的结果:
2018-09-13 14:10:25.569903+0800 ios-005[3023:294900] 1
2018-09-13 14:10:25.570009+0800 ios-005[3023:294900] 2
2018-09-13 14:10:25.570085+0800 ios-005[3023:294900] 3
2018-09-13 14:10:25.570168+0800 ios-005[3023:294900] 4
2018-09-13 14:10:25.570238+0800 ios-005[3023:294900] 5
(2)可以选择顺序的遍历写法(正向排序法)
[arrayabc enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%@",obj);
}];
打印的结果:
2018-09-13 14:11:01.782222+0800 ios-005[3023:294951] 1
2018-09-13 14:11:11.328628+0800 ios-005[3023:294900] 2
2018-09-13 14:11:11.328667+0800 ios-005[3023:296137] 3
2018-09-13 14:11:11.328669+0800 ios-005[3023:296139] 5
2018-09-13 14:11:11.328679+0800 ios-005[3023:296138] 4
(3)可以选择顺序的遍历写法(反向排序法)
[arrayabc enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%@",obj);
}];
打印的结果:
2018-09-13 14:12:04.873126+0800 ios-005[3023:294900] 5
2018-09-13 14:12:07.788884+0800 ios-005[3023:294900] 4
2018-09-13 14:12:07.789148+0800 ios-005[3023:294900] 3
2018-09-13 14:12:07.789311+0800 ios-005[3023:294900] 2
2018-09-13 14:12:07.789498+0800 ios-005[3023:294900] 1
(3)可以选择顺序和选择范围的遍历写法(正向排序法)
[arrayabc enumerateObjectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0,2)] options:NSEnumerationConcurrent usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%@",obj);
}];
打印的结果:
2018-09-13 14:12:54.615645+0800 ios-005[3023:294900] 1
2018-09-13 14:12:58.197195+0800 ios-005[3023:294900] 2
(4)可以选择顺序和选择范围的遍历写法(反向排序法)
[arrayabc enumerateObjectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0,2)] options:NSEnumerationReverse usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%@",obj);
}];
打印的结果:
2018-09-13 14:13:31.503515+0800 ios-005[3023:294900] 2
2018-09-13 14:13:37.217698+0800 ios-005[3023:294900] 1
网友评论