NSArray的方法交换技术

4

我正在尝试调试一个NSArray的问题,但是我甚至找不到引起问题的数组指针,并且我不知道为什么会出现这种情况。我在objectAtIndex:(越界)上收到一个错误,似乎是来自某个内部NSView方法...无论如何,我尝试使用自己的方法替换objectAtIndex:,但它不起作用。奇怪的是,我可以做同样的事情,但是使用另一个类和方法,它可以正常工作。这是我用于交换的代码:

Class arrayClass = [NSArray class];
Method originalMethod = class_getClassMethod(arrayClass, @selector(objectAtIndex:));
Method categoryMethod = class_getClassMethod(arrayClass, @selector(objectAtIndexAlt:));
method_exchangeImplementations(originalMethod, categoryMethod);

它不起作用。有人知道为什么吗?

更新:谢谢Dave,那可能是问题所在。我还写成了getClassMethod而不是instance。无论如何,这是我最终的解决方案:

#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);
}
2个回答

8
当你创建一个数组时,你不会得到一个NSArray的实例。通常你得到的是NSCFArray,尽管还有其他私有类,比如__NSArrayM等等。 这是因为NSArray是一个类簇

0
Dave DeLong说得对。我认为你正在寻找一种聚合的方法,可以看看NSObjectSafe,它是一个微小的开源框架,钩取了Foundation容器的大多数常用函数,例如[NSArray objectAtIndex:]。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接