// // NSMutableArray+RQSafe.m // jiaPei // // Created by 张嵘 on 2019/4/2. // Copyright © 2019 JCZ. All rights reserved. // #import "NSMutableArray+RQSafe.h" @implementation NSMutableArray (RQSafe) static char const *name = "__NSArrayM"; + (void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ [objc_getClass(name) methodSwizzlingWithOriginalSelector:@selector(addObject:) bySwizzledSelector:@selector(safeAddObject:)]; [objc_getClass(name) methodSwizzlingWithOriginalSelector:@selector(removeObject:) bySwizzledSelector:@selector(safeRemoveObject:)]; [objc_getClass(name) methodSwizzlingWithOriginalSelector:@selector(removeObjectAtIndex:) bySwizzledSelector:@selector(safeRemoveObjectAtIndex:)]; [objc_getClass(name) methodSwizzlingWithOriginalSelector:@selector(insertObject:atIndex:) bySwizzledSelector:@selector(safeInsertObject:atIndex:)]; [objc_getClass(name) methodSwizzlingWithOriginalSelector:@selector(objectAtIndex:) bySwizzledSelector:@selector(safeObjectAtIndex:)]; }); } - (void)safeAddObject:(id)obj { if (obj == nil) { NSLog(@"%s can add nil object into NSMutableArray", __FUNCTION__); return; } [self safeAddObject:obj]; } - (void)safeRemoveObject:(id)obj { if (obj == nil) { NSLog(@"%s call -removeObject:, but argument obj is nil", __FUNCTION__); return; } [self safeRemoveObject:obj]; } - (void)safeRemoveObjectAtIndex:(NSUInteger)index { if (self.count <= 0) { NSLog(@"%s can't get any object from an empty array", __FUNCTION__); } else if (index >= self.count) { NSLog(@"%s index out of bound", __FUNCTION__); } else { [self safeRemoveObjectAtIndex:index]; } } - (void)safeInsertObject:(id)anObject atIndex:(NSUInteger)index { if (anObject == nil) { NSLog(@"%s can't insert nil into NSMutableArray", __FUNCTION__); } else if (index > self.count) { NSLog(@"%s: index is invalid", __FUNCTION__); } else { [self safeInsertObject:anObject atIndex:index]; } } - (id)safeObjectAtIndex:(NSUInteger)index { if (self.count == 0) { NSLog(@"%s can't get any object from an empty array", __FUNCTION__); return nil; } else if (index > self.count - 1) { // [__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1] NSLog(@"%s: index %ld beyond bounds [0..%ld]", __FUNCTION__, index, self.count); return nil; } else { return [self safeObjectAtIndex:index]; } } @end