NSMutableArray+RQSafe.m 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //
  2. // NSMutableArray+RQSafe.m
  3. // jiaPei
  4. //
  5. // Created by 张嵘 on 2019/4/2.
  6. // Copyright © 2019 JCZ. All rights reserved.
  7. //
  8. #import "NSMutableArray+RQSafe.h"
  9. @implementation NSMutableArray (RQSafe)
  10. static char const *name = "__NSArrayM";
  11. + (void)load {
  12. static dispatch_once_t onceToken;
  13. dispatch_once(&onceToken, ^{
  14. [objc_getClass(name) methodSwizzlingWithOriginalSelector:@selector(addObject:) bySwizzledSelector:@selector(safeAddObject:)];
  15. [objc_getClass(name) methodSwizzlingWithOriginalSelector:@selector(removeObject:) bySwizzledSelector:@selector(safeRemoveObject:)];
  16. [objc_getClass(name) methodSwizzlingWithOriginalSelector:@selector(removeObjectAtIndex:) bySwizzledSelector:@selector(safeRemoveObjectAtIndex:)];
  17. [objc_getClass(name) methodSwizzlingWithOriginalSelector:@selector(insertObject:atIndex:) bySwizzledSelector:@selector(safeInsertObject:atIndex:)];
  18. [objc_getClass(name) methodSwizzlingWithOriginalSelector:@selector(objectAtIndex:) bySwizzledSelector:@selector(safeObjectAtIndex:)];
  19. });
  20. }
  21. - (void)safeAddObject:(id)obj {
  22. if (obj == nil) {
  23. NSLog(@"%s can add nil object into NSMutableArray", __FUNCTION__);
  24. return;
  25. }
  26. [self safeAddObject:obj];
  27. }
  28. - (void)safeRemoveObject:(id)obj {
  29. if (obj == nil) {
  30. NSLog(@"%s call -removeObject:, but argument obj is nil", __FUNCTION__);
  31. return;
  32. }
  33. [self safeRemoveObject:obj];
  34. }
  35. - (void)safeRemoveObjectAtIndex:(NSUInteger)index {
  36. if (self.count <= 0) {
  37. NSLog(@"%s can't get any object from an empty array", __FUNCTION__);
  38. } else if (index >= self.count) {
  39. NSLog(@"%s index out of bound", __FUNCTION__);
  40. } else {
  41. [self safeRemoveObjectAtIndex:index];
  42. }
  43. }
  44. - (void)safeInsertObject:(id)anObject atIndex:(NSUInteger)index {
  45. if (anObject == nil) {
  46. NSLog(@"%s can't insert nil into NSMutableArray", __FUNCTION__);
  47. } else if (index > self.count) {
  48. NSLog(@"%s: index is invalid", __FUNCTION__);
  49. } else {
  50. [self safeInsertObject:anObject atIndex:index];
  51. }
  52. }
  53. - (id)safeObjectAtIndex:(NSUInteger)index {
  54. if (self.count == 0) {
  55. NSLog(@"%s can't get any object from an empty array", __FUNCTION__);
  56. return nil;
  57. } else if (index > self.count - 1) {
  58. // [__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]
  59. NSLog(@"%s: index %ld beyond bounds [0..%ld]", __FUNCTION__, index, self.count);
  60. return nil;
  61. } else {
  62. return [self safeObjectAtIndex:index];
  63. }
  64. }
  65. @end