Swizzling Method for NSArray

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); } 
+4
source share
2 answers

When you create an array, you are not getting an instance of NSArray . Usually you get NSCFArray , although there are other private classes like __NSArrayM etc.

This is because NSArray is a class cluster .

+7
source

Dave DeLong is right. I think you're looking for a way to tilt the cluster, take a look at NSObjectSafe , it is a tiny open source environment that captures most of the commonly used Foundation container function, such as [NSArray objectAtIndex:]

0
source

Source: https://habr.com/ru/post/1369345/


All Articles