gpt4 book ai didi

swift - Kotlin-Swift 互操作问题 : ArrayList has wrong count value when passed as NSMutableArray from Swift Code for Release builds

转载 作者:行者123 更新时间:2023-12-02 12:44:12 25 4
gpt4 key购买 nike

让我们假设一个 KMP 项目设置为有一个示例 iOS 应用程序,其中 KMP 模块的输出框架被添加为依赖项。

我有一个函数 sampleFuncForStringArrayList(names: ArrayList<String>)在打印计数、迭代和打印 ArrayList 项目的 KMP 模块中。

当我从 iOS 示例应用程序调用此函数时,出现索引超出范围异常因为 NSMutableArray count在 iOS 应用程序环境中为 2,有 count在 KMP 模块中作为 ArrayList 接收时为 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")
}
}
}

预期输出

NSMutableArray COUNT : 2
names.isNullOrEmpty() false
names.count 2
Hello Alice
Hello Bob

实际输出:

NSMutableArray COUNT : 2
names.isNullOrEmpty() false
names.count 24576
CRASH

- CRASH -

示例项目 zip :https://drive.google.com/file/d/1SgmW4hfeWaEeD3vcidnZ81Q9vMJsU9zJ/view?usp=sharing

最佳答案

我已经尝试过我的 KMM 设置(使用 cocoapods),即使是发布版本,我也得到了正确的预期行为,但我使用了正确的 kotlin/swift interop mapping输入 MutableList

fun sampleFuncForStringMutableList(names: MutableList<String>) {
println("names.isNullOrEmpty() ${names.isNullOrEmpty()}")
println("names.count ${names.count()}")
names.forEach {
println("Hello $it")
}
}

使用 ArrayList 我看到一个空数组,然后崩溃(与我看到您预期行为的调试版本不同)。

let namesStringList = NSMutableArray(array: ["Alice", "Bob"])
print("NSMutableArray COUNT : \(namesStringList.count)")
Main().sampleFuncForStringArrayList(names: namesStringList)
Main().sampleFuncForStringMutableList(names: namesStringList)
NSMutableArray COUNT : 2
names.isNullOrEmpty() true
names.count 0
names.isNullOrEmpty() false
names.count 2
Hello Alice
Hello Bob

所以我建议您使用正确的映射类型,而不是另一种。

关于swift - Kotlin-Swift 互操作问题 : ArrayList has wrong count value when passed as NSMutableArray from Swift Code for Release builds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63832362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com