Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method swizzling for NSArray

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?

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);
}
like image 943
anon Avatar asked Feb 23 '23 03:02

anon


1 Answers

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.

That's because NSArray is a class cluster.

like image 90
Dave DeLong Avatar answered Mar 02 '23 00:03

Dave DeLong