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

如何在KMM中通过类名字符串创建Objective-C类实例?

在KMM中通过类名字符串创建Objective-C类实例的实现方案

完全可行,在KMM的iOS目标代码中,我们可以借助Objective-C的运行时API,实现通过类名字符串动态创建OC类实例。

核心实现代码

直接修改你提供的函数,结合Objective-C运行时方法即可完成:

import platform.Foundation.NSObject
import platform.objc.objc_getClass
import platform.objc.sel_registerName
import platform.objc.msgSend

fun createObject(className: String): Any? {
    // 通过类名字符串获取OC类对象
    val ocClass = objc_getClass(className) ?: return null
    // 获取alloc方法选择器
    val allocSelector = sel_registerName("alloc")
    // 调用alloc分配实例内存
    val allocatedInstance = msgSend(ocClass, allocSelector)
    // 获取init方法选择器
    val initSelector = sel_registerName("init")
    // 调用init初始化实例并返回
    return msgSend(allocatedInstance, initSelector)
}

关键注意事项

  • OC类暴露要求:你要实例化的Objective-C类必须继承自NSObject,并且确保已经通过KMM的interop机制暴露给Kotlin代码(比如自动生成的桥接文件或手动配置的.def文件)。
  • 自定义初始化方法:如果目标类需要用带参数的初始化方法(比如initWithName:),只需替换对应的选择器字符串,并在msgSend中传入参数即可。
  • 平台兼容性:上述代码仅能在KMM的iOS目标中运行,在Android目标中需要通过expect/actual机制做平台区分:

跨平台适配示例

  1. 通用模块定义expect函数:
expect fun createObject(className: String): Any?
  1. iOS模块实现actual函数:
import platform.Foundation.NSObject
import platform.objc.objc_getClass
import platform.objc.sel_registerName
import platform.objc.msgSend

actual fun createObject(className: String): Any? {
    val ocClass = objc_getClass(className) ?: return null
    val allocSelector = sel_registerName("alloc")
    val allocatedInstance = msgSend(ocClass, allocSelector)
    val initSelector = sel_registerName("init")
    return msgSend(allocatedInstance, initSelector)
}
  1. Android模块实现actual函数:
actual fun createObject(className: String): Any? {
    // Android端无对应Objective-C类,返回null或按需处理
    return null
}

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 09:30:16