Is it possible to swizzle the addObject: method of NSMutableArray?
Here is what I am trying.
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@implementation NSMutableArray (LoggingAddObject)
+ (void)load {
Method addObject = class_getInstanceMethod(self, @selector(addObject:));
Method logAddObject = class_getInstanceMethod(self, @selector(logAddObject:));
method_exchangeImplementations(addObject, logAddObject);
Method original = class_getInstanceMethod(self, @selector(setObject:atIndexedSubscript:));
Method swizzled = class_getInstanceMethod(self, @selector(swizzled_setObject:atIndexedSubscript:));
method_exchangeImplementations(original, swizzled);
}
- (void)logAddObject:(id)anObject {
[self logAddObject:anObject];
NSLog(@"Added object %@ to array %@", anObject, self);
}
-(void)swizzled_setObject:(id)obj atIndexedSubscript:(NSUInteger)idx
{
NSLog(@"This gets called as expected!!-----");
[self swizzled_setObject:obj atIndexedSubscript:idx];
}
I am able to swizzle some of the methods like setObject:atIndexedSubscript: but I am worried that I cant do it do the addObject: and others. I think the below can not be swizzled? Can someone explain why ? what I am doing wrong and or a way around this?
/**************** Mutable Array ****************/
@interface NSMutableArray : NSArray
- (void)addObject:(id)anObject;
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;
- (void)removeLastObject;
- (void)removeObjectAtIndex:(NSUInteger)index;
- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
@end