I am trying to debug something in NSArray, and I canβt even find that the pointer to the array is causing the problem, and I have no idea why this is happening. I get the error objectAtIndex: (out of bounds), and it seems to come from some kind of internal NSView method ... anyway, I tried swizzling objectAtIndex: with my own, but that won't work. What is strange, I can do the same, but with a different class and method, and it works fine. Here is what I do to swizzle:
Class arrayClass = [NSArray class]; Method originalMethod = class_getClassMethod(arrayClass, @selector(objectAtIndex:)); Method categoryMethod = class_getClassMethod(arrayClass, @selector(objectAtIndexAlt:)); method_exchangeImplementations(originalMethod, categoryMethod);
and it does not work. Does anyone know why?
update: thanks to Dave, this is probably the problem. I also had getClassMethod instead of instance. Anyway, here is what I did:
#import <Cocoa/Cocoa.h> #import <objc/runtime.h> @interface NSArray (Swizzle) - (void)objectAtIndexAlt:(NSUInteger)index; @end @implementation NSArray (Swizzle) - (void)objectAtIndexAlt:(NSUInteger)index { if ([self count] <= index) NSLog(@"%s self = %@, pointer = %p, index = %lu", __FUNCTION__, self, self, (unsigned long)index); return [self objectAtIndexAlt:index]; } @end int main(int argc, char *argv[]) { Class arrayClass = NSClassFromString(@"__NSArrayM"); Method originalMethod = class_getInstanceMethod(arrayClass, @selector(objectAtIndex:)); Method categoryMethod = class_getInstanceMethod([NSArray class], @selector(objectAtIndexAlt:)); method_exchangeImplementations(originalMethod, categoryMethod); return NSApplicationMain(argc, (const char **) argv); }
source share