NSArray+RQExtension.m 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //
  2. // NSArray+RQExtension.m
  3. // XinShouJiaDao
  4. //
  5. // Created by 张嵘 on 2021/7/7.
  6. // Copyright © 2021 JCZ. All rights reserved.
  7. //
  8. #import "NSArray+RQExtension.h"
  9. @implementation NSArray (RQExtension)
  10. -(id)objAtPath:(NSIndexPath*)path
  11. {
  12. if (path.section < self.count ) {
  13. NSArray* subObj = self[path.section];
  14. if([subObj isKindOfClass:[NSArray class]] ||
  15. [subObj isKindOfClass:[NSMutableArray class]])
  16. {
  17. if (path.row < subObj.count) {
  18. return [self[path.section] objectAtIndex:path.row];
  19. }
  20. }
  21. }
  22. return nil;
  23. }
  24. /*
  25. * @brief 将数组随机打乱
  26. */
  27. - (NSArray *)rq_randomArray {
  28. // 转为可变数组
  29. NSMutableArray * tmp = self.mutableCopy;
  30. // 获取数组长度
  31. NSInteger count = tmp.count;
  32. // 开始循环
  33. while (count > 0) {
  34. // 获取随机角标
  35. NSInteger index = arc4random_uniform((int)(count - 1));
  36. // 获取角标对应的值
  37. id value = tmp[index];
  38. // 交换数组元素位置
  39. tmp[index] = tmp[count - 1];
  40. tmp[count - 1] = value;
  41. count --;
  42. }
  43. // 返回打乱顺序之后的数组
  44. return tmp.copy;
  45. }
  46. #pragma mark -- 数组排序方法(升序)
  47. - (NSArray *)arraySortASC {
  48. return [self sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
  49. return [obj1 compare:obj2];
  50. }];
  51. }
  52. #pragma mark -- 数组排序方法(降序)
  53. - (NSArray *)arraySortDESC{
  54. return [self sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
  55. return [obj2 compare:obj1];
  56. }];
  57. }
  58. #pragma mark -- 数组排序方法(乱序)
  59. - (NSArray *)arraySortBreak {
  60. return [self sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
  61. if (arc4random_uniform(2) == 0) {
  62. return [obj2 compare:obj1]; //降序
  63. } else {
  64. return [obj1 compare:obj2]; //升序
  65. }
  66. }];
  67. }
  68. @end