在Objective-C,iOS 9中进行高级方法调整?

问题很简单.我需要和通常一样 – 如何在iOS9中用@selector(presentViewController:animated:completion :)替换原来的方法?它仅适用于iOS9模拟器,不适用于真实设备.

是的,这个代码被调用但是你得到了EXC_BAD_ACCESS.

为了测试它我从“Master-Detail模板”创建了一个测试应用程序,添加了一个按钮并添加了以下代码:

UIViewController *vc = [[UIViewController alloc] init];
[self.navigationController presentViewController:vc animated:YES completion:nil];

更新

@implementation UINavigationController (Extension)

- (void)swizzledPresentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion
{
    [ self swizzledPresentViewController:viewControllerToPresent animated:flag completion:completion ];
}

#pragma mark -

+ (void)swizzle:(Class)class oldSelector:(SEL)old newSelector:(SEL)new
{
    Method oldMethod = class_getInstanceMethod(class, old);
    Method newMethod = class_getInstanceMethod(class, new);


    if(class_addMethod(class, old, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
    {
        class_replaceMethod(class, new, method_getImplementation(oldMethod), method_getTypeEncoding(oldMethod));
    }
    else
    {
        method_exchangeImplementations(oldMethod, newMethod);
    }
}

+ (void)load
{
    [self swizzle:UINavigationController.class oldSelector:@selector(presentViewController:animated:completion:) newSelector:@selector(swizzledPresentViewController:animated:completion:)];
}

@end

几乎相同的代码写在NSHipster网站上

更新

警告!这个错误在非常随机的设备上重现(在我的例子中它是iphone5 ios9.0,但其他用户有更新的设备和iOS9.1).

最佳答案 问题是调查nil值的调整.这种情况的解决方案:

1)检查块是否为零然后用空的非零块替换它

2)使用现成的库.我试过了:https://github.com/rabovik/RSSwizzle

点赞