I am having trouble calling certain iOS functions ...
# ios
h
I am having trouble calling certain iOS functions from Kotlin/Native How would I for example call this method? https://developer.apple.com/documentation/foundation/nsstring/1407654-write I have tried using variations like this, but it does not seem to compile no matter what I try:
val contents = "File contents"
val filename = "some.file"
val res = contents.writeToFile(filename, true, NSUTF8StringEncoding)
I have succeeded using the simpler overload without encoding end error, but the
NSError*/throws
is causing me problems. How can I supply/catch that parameter from Kotlin?
a
Hi! As there is a pointer to
NSError
in the function signature, one should allocate the object in native memory, and then pass it to the function. For example, like
Copy code
memScoped {
    val error = alloc<ObjCObjectVar<NSError?>>()
    ("SampleText" as NSString).writeToFile(
        path ="/absolute/path/toWrite/text",
        atomically =true,
                    encoding = NSUTF8StringEncoding,
        error =error.ptr)
    println(error.value)
}
h
OK, thanks. I will try that later 🙂 Do I need to free up the memory myself since it is called using alloc, or will that be reclaimed automatically?
a
If it is done in the
memScoped
block, it will be released automatically as soon as the block ends. There are other ways to work with native memory in K/N, see here(https://github.com/JetBrains/kotlin-native/blob/v1.3.60/INTEROP.md#memory-allocation) and here(https://kotlinlang.org/api/latest/jvm/stdlib/kotlinx.cinterop/-arena/index.html).
h
Thank you!