I've got an immutable data class that I'm sharing ...
# ios
n
I've got an immutable data class that I'm sharing with swift. When I'm creating an instance of that class and access it from another thread I get the 'illegal attempt to access non-shared object' error. How can I share this instance between threads in swift?
k
If you’re not using the new memory model, you’ll need to adhere to the strict memory model rules. That means, in summary, you’ll need to freeze the data object when returning it from Kotlin. Alternatively, use the new memory model: https://blog.jetbrains.com/kotlin/2021/08/try-the-new-kotlin-native-memory-manager-development-preview/
For the “strict” model, I have a whole bunch of various bits of docs trying to explain it: https://dev.to/touchlab/practical-kotlin-native-concurrency-ac7
n
Thanks! I'm directly invoking kotlin's initializer from swift, so no possibility to use freeze there, right? Should I provide extra swift functions that freeze before returning?
k
Hmm. You could probably do something like this. Not the most elegant, but should work. Either freeze in init block, or have a base class that does:
Copy code
data class SomeData(val s:String){
    init {
        freeze()
    }
}

abstract class FrozenBase{
    init {
        freeze()
    }
}

data class SomeData2(val s:String):FrozenBase()
The base class might not work if it calls init on that before it sets the values in the subclass, though.
In my usage, we’re generally calling something that returns values rather than creating them directly, so I dont’ run into this much.
n
I'll have a try later, thanks!
I switched to the new memory model, that seems to work perfectly!
Copy code
targets.withType(KotlinNativeTarget::class.java) {
        binaries.all {
            binaryOptions["memoryModel"] = "experimental"
        }
    }
👍 1