简体   繁体   中英

How to swizzle []method of NSArray in iOS11?

I used to hack the method like

Method originalMethod = class_getInstanceMethod([NSArray class], @selector(objectAtIndexedSubscript:));
Method swapMethod = class_getInstanceMethod([NSArray class], @selector(objectAtIndexedSubscriptNew:));
method_exchangeImplementations(originalMethod, swapMethod);

It works fine in the iOS10 and before, but it can't work in the iOS11, is that any other way we can swizzle the [] method in iOS11?

As of iOS 11, for some reason that I'm still researching, swizzle methods should only be called once.

static dispatch_once_t once;
dispatch_once(&once, ^{    
    Method originalMethod = class_getInstanceMethod([NSArray class], @selector(objectAtIndexedSubscript:));
    Method swapMethod = class_getInstanceMethod([NSArray class], @selector(objectAtIndexedSubscriptNew:));
    method_exchangeImplementations(originalMethod, swapMethod);
});

我将类从[NSArray class]更改为NSClassFromString(@"__NSArrayI")并且它现在工作正常。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM