![](/img/trans.png)
[英]KMM: How to reference the shared module into an already existing iOS project
[英]How to read an array of objectes generated in a Swift framework library, in a KMM (kotlin native) shared module
我正在開發 KMM 應用程序。 共享模塊有一個幫助器 class,它依賴於 android 部件和 iOS 部件的不同本機庫。 這是通過已知的“預期/實際”模式實現的。
如前所述,iOS 實際 class 使用了 iOS 框架,該框架執行一些計算,並返回一個對象數組。 創建對象列表的 ios 框架工作正常(已通過單元測試進行測試)。 下面是一個簡化的示例。
這是數組內部對象的 class:
public class ChildNodeIos: NSObject{
public let content:String
public let isTextNode:Bool
public init(content:String,isTextNode:Bool=false){
self.content=content
self.isTextNode=isTextNode
}
}
返回對象列表的 iOS 端的助手 class 將類似於:
@objc public class IOSCoolHelper: NSObject {
@objc public func getChildNodes(message: String) -> [ChildNodeIos] {
//build the array of child nodes here and return them
}
}
在 kotlin 共享模塊中,在 iOS 內部預期 class,ZC1C425268E68385D14AB5074C17ZA 如下所示:
@Serializable
data class ChildNodeKN(val content :String,val isTextNode :Boolean=false)
import com.mydomain.iosframeworks.IosCoolHelper
actual class CoolHelper actual constructor(private val someStuff: String) : ICoolHelper {
actual override fun getChildNodes(message: String): List<ChildNodeKN> {
val iosHelper= IOSCoolHelper()
val swiftarray:List<ChildNodeIos> = iosHelper.getChildNodes(message)
//I was expecting to do something like that but it does not work (the content of "array is always empty"):
val kotlinList:List<ChildNodeKN> = swiftarray as List<ChildNodeIos>
return kotlinList
}
}
}
Or maybe if the list of swift objects can not be direct be casted to the equivalent kotlin object list, I was expecting to be able to iterate over the swift list and convert it to the kotlin list, something like that:
val kotlinList=mutableListOf<ChildNodeKN>()
swiftArray.foreach{
kotlinList.add(ChildNodeKN(it.content,it.isTextNode))
}
但同樣,swift 數組的內容是空的。 做了很多測試(我現在無法重現它們),我設法訪問了數組內部的一些東西,但它不是 ChildNodeIos 類型的 object,也不是我在 kotlin 端讀不到的東西。
好吧,問題是,如何在 kotlin 端接收在 iOS 端生成的內部或多或少復雜對象的列表?
我不得不說,這個 swift 助手 class 具有許多其他返回原始值(字符串、布爾值或 int)的函數,並且運行良好。
我想一個解決方法將是一個包含對象的數組,從 Swift 端返回一個具有基本類型和二維的數組,但如果可能的話,我想使用一個對象數組。
謝謝您的幫助
我設法自己找到了解決方案。 問題是列表中包含的 object 的 Swift class 的聲明。 我忘記了 class 屬性的 @objc 聲明,因為如果那樣我就無法讀取返回數組中的對象。
公共 class ChildNodeIos:NSObject{
@objc public let content:String
@objc public let isTextNode:Bool
public init(content:String,isTextNode:Bool=false){
self.content=content
self.isTextNode=isTextNode
}
}
然后,在 Kotlin 方面,我沒有實現將其直接轉換為列表,但使用 foreach 循環很容易在 Kotlin 對象中編寫 iOS 對象:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.