NSArray方法陷入困境 [英] Method swizzling for NSArray

查看:100
本文介绍了NSArray方法陷入困境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在NSArray上调试某些东西,甚至找不到导致问题的数组的指针,我也不知道为什么会发生.我在objectAtIndex:上出现错误((越界),它似乎来自某些内部NSView方法...无论如何,我尝试用自己的方法刷新objectAtIndex:,但无法正常工作.奇怪的是,我可以执行相同的操作,但是可以使用另一个类和方法,并且可以正常工作.这是我正在做的事情:

I'm trying to debug something on an NSArray and I can't even find what the pointer to the array that's causing the issue is and I have no idea why it's happening. I'm getting an error on objectAtIndex: (out of bounds) and it seems to be coming from some internal NSView method... anyway, I tried swizzling objectAtIndex: with my own, but it won't work. What's strange is I can do the same thing but with another class and method, and it works fine. Here's what I'm doing 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 isn't working. Does anyone know why?

更新:谢谢戴夫,这可能是问题所在.我也有getClassMethod而不是实例.无论如何,这就是我最终要做的事情:

update: thanks Dave, that was probably the issue. I also had getClassMethod instead of instance. Anyway, here's what I ended up doing:

#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);
}

推荐答案

创建数组时,不会获得NSArray的实例.尽管还有其他私有类,例如__NSArrayM等,您通常会得到一个NSCFArray.

When you create an array, you don't get an instance of NSArray. You usually get an NSCFArray, although there are other private classes, like __NSArrayM and so on.

这是因为NSArray类集群.

这篇关于NSArray方法陷入困境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆