Today I was working on a project in which I wanted to \"alias\" an alternative method for all instances of NSArray
, and didn\'t think it would be too difficult with
Presumably you have a particular array for which you'd like this behavior. You can get that instance's class object, no matter what it is, and swizzle that quite easily:
[[myArray class] jr_swizzleMethod:@selector(objectAtIndex:) withMethod:@selector(objectAtIndex_accordingToMe:) error:nil];
There's also only a few concrete subclasses of NSArray
:
NSArray * trees = [NSArray array];
NSArray * birds = [NSArray arrayWithObjects:@"Albatross", @"Budgerigar", @"Cardinal", nil];
NSMutableArray * dogs = [NSMutableArray arrayWithObjects:@"Airedale", @"Beagle", @"Collie", nil];
NSLog(@"%@ %@ %@", [trees class], [birds class], [dogs class]);
We get __NSArrayI
for the first two and __NSArrayM
for the third, so potentially (this is very fragile) you could use a runtime function to grab the class object by name:
[objc_getClass("__NSArrayI") jr_swizzleMethod:@selector(objectAtIndex:) withMethod:@selector(objectAtIndex_accordingToMe:) error:nil];