我正在尝试在 NSArray 上调试某些东西,但我什至找不到导致问题的数组指针是什么,我不知道为什么会这样。我在 objectAtIndex: (out of bounds) 上遇到错误,它似乎来自一些内部 NSView 方法......无论如何,我尝试使用自己的方法调整 objectAtIndex: ,但它不起作用。奇怪的是我可以用另一个类和方法做同样的事情,而且效果很好。这是我正在做的调酒:
Class arrayClass = [NSArray class];
Method originalMethod = class_getClassMethod(arrayClass, @selector(objectAtIndex:));
Method categoryMethod = class_getClassMethod(arrayClass, @selector(objectAtIndexAlt:));
method_exchangeImplementations(originalMethod, categoryMethod);
它不工作。有谁知道为什么?
更新:谢谢戴夫,这可能是问题所在。我也有 getClassMethod 而不是实例。无论如何,这就是我最终做的事情:
#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);
}