#import <objc/runtime.h>
+(void)load
{
staticdispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// When swizzling a class method, use the following:
[selfreplaceSelector:@selector(addObject:)withSelector:@selector(safe_addObject:)];
[selfreplaceSelector:@selector(objectAtIndex:)withSelector:@selector(safe_objectAtIndex:)];
[selfreplaceSelector:@selector(removeObjectAtIndex:)withSelector:@selector(safe_removeObjectAtIndex:)];
});
}
+ (BOOL)replaceSelector:(SEL)originalSel withSelector:(SEL)swizzledSel
{
// Class class = object_getClass((id)self);
Class class = NSClassFromString(@"__NSArrayM"); //__NSArrayM 是NSMutableArray __NSArrayI:是NSArray
Method originalMethod = class_getInstanceMethod(self, originalSel);
if (!originalMethod) {
return NO;
}
Method swizzleMethod = class_getInstanceMethod(self, swizzledSel);
if (!swizzleMethod) {
return NO;
}
class_addMethod(self,
originalSel,
class_getMethodImplementation(self, originalSel),
method_getTypeEncoding(originalMethod));
class_addMethod(self,
swizzledSel,
class_getMethodImplementation(self, swizzledSel),
method_getTypeEncoding(swizzleMethod));
method_exchangeImplementations(originalMethod, swizzleMethod);
return YES;
}
- (void)safe_addObject:(id)object
{
if (object ==nil) {
NSLog(@"%@ : add nil object",NSStringFromSelector(_cmd));
return;
}
[selfsafe_addObject:object];
}
- (id)safe_objectAtIndex:(NSInteger)index
{
if (index >= [selfcount]) {
NSLog(@"%@ : index greater count",NSStringFromSelector(_cmd));
returnnil;
}
return [selfsafe_objectAtIndex:index];
}
- (void)safe_removeObjectAtIndex:(NSInteger)index
{
if (index >= [selfcount]) {
NSLog(@"%@ : index greater count",NSStringFromSelector(_cmd));
return;
}
[selfsafe_removeObjectAtIndex:index];
}