Ale*_*lex 4 interop kotlin swift kotlin-native kotlin-multiplatform
我们假设一个 KMP 项目设置为具有示例 iOS 应用程序,其中添加了 KMP 模块的输出框架作为依赖项。
我在 KMP 模块中有一个函数sampleFuncForStringArrayList(names: ArrayList<String>),可以打印计数、迭代和打印 ArrayList 项目。
当我从 iOS 示例应用程序调用此函数时,我收到索引越界异常,因为 NSMutableArray在 iOS 应用程序环境中count为2,而在 KMP 模块中作为 ArrayList 接收时count为24576 。
此问题仅发生在releaseFramework 中。debugFramework工作正常。
//Swift
let namesStringList = NSMutableArray(array: ["Alice", "Bob"])
print("NSMutableArray COUNT : \(namesStringList.count)")
Main().sampleFuncForStringArrayList(names: namesStringList)
//Kotlin
public class Main {
public fun sampleFuncForStringArrayList(names: ArrayList<String>){
println("names.isNullOrEmpty() ${names.isNullOrEmpty()}")
println("names.count ${names.count()}")
names.forEach {
println("Hello $it")
}
}
}
Run Code Online (Sandbox Code Playgroud)
预期输出
NSMutableArray COUNT : 2
names.isNullOrEmpty() false
names.count 2
Hello Alice
Hello Bob
Run Code Online (Sandbox Code Playgroud)
实际输出:
NSMutableArray COUNT : 2
names.isNullOrEmpty() false
names.count 24576
CRASH
Run Code Online (Sandbox Code Playgroud)
示例项目 ZIP:https://drive.google.com/file/d/1SgmW4hfeWaEeD3vcidnZ81Q9vMJsU9zJ/view ?usp=sharing
我尝试过 KMM 设置(使用 cocoapods),即使使用发布版本,我也得到了正确的预期行为,但我使用了正确的kotlin/swift 互操作映射类型MutableList
fun sampleFuncForStringMutableList(names: MutableList<String>) {
println("names.isNullOrEmpty() ${names.isNullOrEmpty()}")
println("names.count ${names.count()}")
names.forEach {
println("Hello $it")
}
}
Run Code Online (Sandbox Code Playgroud)
我看到ArrayList一个空数组,然后崩溃(与调试构建不同,我也看到了您的预期行为)。
let namesStringList = NSMutableArray(array: ["Alice", "Bob"])
print("NSMutableArray COUNT : \(namesStringList.count)")
Main().sampleFuncForStringArrayList(names: namesStringList)
Main().sampleFuncForStringMutableList(names: namesStringList)
Run Code Online (Sandbox Code Playgroud)
NSMutableArray COUNT : 2
names.isNullOrEmpty() true
names.count 0
names.isNullOrEmpty() false
names.count 2
Hello Alice
Hello Bob
Run Code Online (Sandbox Code Playgroud)
因此,我建议您使用正确的映射类型,而不是其他映射类型。
| 归档时间: |
|
| 查看次数: |
850 次 |
| 最近记录: |