1 #import "HMViewController.h" 2 3 @interface HMViewController () 4 5 @end 6 7 @implementation HMViewController 8 9 - (void)viewDidLoad 10 { 11 [super viewDidLoad]; 12 13 // 块代码 14 NSArray *array = @[@(1), @(2), @(3), @(4), @(5)]; 15 16 // 排序 17 array = [array sortedArrayUsingComparator:^NSComparisonResult(NSNumber *num1, NSNumber *num2) { 18 19 // 乱序=>一会升序,一会降序 20 // 随机 21 // arc4random_uniform(10) => 0~9之间的随机数 22 int seed = arc4random_uniform(2); 23 if (seed) { 24 return [num1 compare:num2]; 25 } else { 26 return [num2 compare:num1]; 27 } 28 }]; 29 30 NSLog(@"%@", array); 31 } 32 33 - (void)sortWith:(NSArray *)array 34 { 35 // 排序 36 array = [array sortedArrayUsingComparator:^NSComparisonResult(NSNumber *num1, NSNumber *num2) { 37 38 /** 39 1 4 5 2 40 4 1 5 2 41 4 1 5 2 42 5 4 1 2 43 5 4 1 2 44 5 4 2 1 45 */ 46 NSLog(@"%@ %@", num1, num2); 47 48 // 升序 49 // return [num1 compare:num2]; 50 // 降序 51 return [num2 compare:num1]; 52 }]; 53 54 NSLog(@"%@", array); 55 } 56 57 - (void)arrayWith:(NSArray *)array 58 { 59 int i = 0; 60 for (NSNumber *num in array) { 61 NSLog(@"%@", num); 62 63 if (i == 1) { 64 break; 65 } 66 i++; 67 } 68 69 // 参数:对象,索引,是否中断 70 // 数组的块方法遍历的效率比for in高 71 [array enumerateObjectsUsingBlock:^(NSNumber *obj, NSUInteger idx, BOOL *stop) { 72 NSLog(@"%@", obj); 73 74 // idx == 1 退出循环 75 if (idx == 1) { 76 *stop = YES; 77 } 78 }]; 79 } 80 81 @end
时间: 2024-12-14 18:44:01