ios - Objective-C、iOS 9 中的高级方法调配?

标签 ios objective-c uiviewcontroller modalviewcontroller method-swizzling

问题很简单。我需要和往常一样 - 如何用我的方法替换原始方法,但 @selector(presentViewController:animated:completion:) 在 iOS9 中?它仅适用于 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)。

最佳答案

问题是 swizzling 中断了检查 nil 值。这种情况的解决方案:

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

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

关于ios - Objective-C、iOS 9 中的高级方法调配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33737213/

相关文章:

iphone - 应用程序在 [scrollView removeFromSuperview] 上崩溃;

objective-c - 如何进入 didSelectAnnotationView 方法?

ios - UIView突然消失了

ios - 当你在第一个 VC 中时,如何在第二个 VC 中运行一个函数?

ios - 在 Firebase/Swift 上为两个匹配的用户创建聊天室的首选方法是什么?

ios - Expo 应用程序 IPA 在我的 iPhone 上无法运行

objective-c - 给定年份使用 iPhone SDK 的天数?

ios - 将数据放入 UIView 容器中的嵌入式 TableView 中

objective-c - 当 UITableview 的部分滚动到顶部时如何获得通知?

ios - 在 Swift 中显示 GoogleMaps View ?