You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xcode 11.4中performSelector触发LLDB RPC服务器崩溃问题求助

解决Xcode 11.4 + Swift 5.2中performSelector获取NSInteger/BOOL返回值时的LLDB崩溃问题

我之前也碰到过一模一样的问题——Xcode 11.3及更早版本完全正常,但升级到11.4后,用performSelector拿基本类型返回值就触发LLDB RPC服务器崩溃。本质原因是**performSelector从设计上就只适合处理返回AnyObject类型的方法**,而NSInteger/BOOL是底层C基本类型(typedef后的int/bool),在Swift 5.2和Xcode 11.4的新调试环境下,这种类型不匹配直接触发了LLDB的bug。

解决方案:改用Objective-C Runtime直接调用方法实现

绕过performSelector,直接通过Runtime获取方法实现并转换成对应类型的函数调用,既能正确处理基本类型返回值,又能避开LLDB的崩溃问题。

处理NSInteger返回值:

if returnReadableType == "NSInteger" {
    guard let method = class_getClassMethod(cls, originalSelector),
          let imp = method_getImplementation(method) else {
        return
    }
    // 定义对应类方法的函数类型
    typealias IntegerClassMethod = @convention(c) (AnyClass, Selector) -> Int
    // 将方法实现转换为可调用的函数
    let invokeMethod = unsafeBitCast(imp, to: IntegerClassMethod.self)
    // 调用方法并获取返回值
    let originalResponse = invokeMethod(cls, originalSelector)
    configDataResult[name] = originalResponse
}

处理BOOL返回值:

else if returnReadableType == "BOOL" {
    guard let method = class_getClassMethod(cls, originalSelector),
          let imp = method_getImplementation(method) else {
        return
    }
    // 定义对应类方法的函数类型
    typealias BoolClassMethod = @convention(c) (AnyClass, Selector) -> Bool
    // 将方法实现转换为可调用的函数
    let invokeMethod = unsafeBitCast(imp, to: BoolClassMethod.self)
    // 调用方法并获取返回值
    let originalResponse = invokeMethod(cls, originalSelector)
    configDataResult[name] = originalResponse
}

为什么这个方法有效?

  1. 直接调用方法实现(method_getImplementation)绕过了performSelector对返回值类型的限制,能正确处理所有C/Swift基本类型和对象类型。
  2. 这种方式更贴合Objective-C Runtime的规范,Apple官方文档也明确指出performSelector系列方法不适合非对象返回值的场景。
  3. 完全避开了Xcode 11.4中LLDB对performSelector返回非对象值的处理bug。

如果你的方法带有参数,只需要修改函数类型的定义即可,比如带一个参数的NSInteger类方法:

typealias IntegerClassMethodWithArg = @convention(c) (AnyClass, Selector, Any) -> Int

内容的提问来源于stack exchange,提问作者Uy Văn Nguyễn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 06:37:43