【发布时间】:2015-11-16 14:01:38
【问题描述】:
问题很简单。我需要和往常一样 - 如何在 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)。
【问题讨论】:
-
向我们展示您是如何进行方法混用的。
-
已编辑。我希望它能帮助找到解决方案
-
你的 swizzled 方法怎么不是无限递归的?
-
???这部分只是意味着我调用了原始方法。
-
@Avi:谷歌关于“方法调配”。那个方法的方法体是用“swizzled”的方法切换的,所以代码实际上调用了原来的方法。
标签: ios objective-c uiviewcontroller modalviewcontroller method-swizzling