【问题标题】:Runtime error when category is added to the UIWebView将类别添加到 UIWebView 时出现运行时错误
【发布时间】:2016-08-09 06:58:29
【问题描述】:

说明

我只是在UIWebView 中添加了一个类别UIWebView+CategoryTest,它使用自定义方法hlz_layoutSubviews 将其转换为layoutSubviews,但UIWebView 从未在我的项目中使用过。当我构建并运行应用程序时,执行[self hlz_layoutSubviews];时出现运行时错误@

CategoryTest[29881:2122091] -[UIWindow hlz_layoutSubviews]:无法识别的选择器发送到实例 0x7f8e73d311e0

我错过了什么吗?

重现问题的步骤

  1. 在 Xcode 中使用 Single View Application 模板创建一个空项目。
  2. 将新类别UIWebView+CategoryTest 添加到UIWebView
  3. UIWebView+CategoryTest.m中的代码替换为以下内容:

```

@implementation UIWebView (CategoryTest)

+ (void)load {
    // Swizzle the `layoutSubviews` method.
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method originalMethod = class_getInstanceMethod(self, @selector(layoutSubviews));
        Method swizzledMethod = class_getInstanceMethod(self, @selector(hlz_layoutSubviews));

        method_exchangeImplementations(originalMethod, swizzledMethod);
    });
}

- (void)hlz_layoutSubviews {
    [self hlz_layoutSubviews];
}

@end

```

  1. Breakpoint navigator 中为All Exceptions 添加Exception Breakpoint
  2. 构建并运行演示应用程序。

【问题讨论】:

    标签: ios objective-c exception uiwebview categories


    【解决方案1】:

    经过与其他开发人员的讨论,原来原因是我在 UIWebView 中调出的方法layoutSubviews 是由它的超类UIView 实现的。所以方法的交换也会影响到UIView的其他子类,比如UIWindow。这样一来,当layoutSubviews 被发送到UIWindow 的实例时,实际上是被混杂的hlz_layoutSubviews 发送给了它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      相关资源
      最近更新 更多