what is the idea around handling objc checked exce...
# kotlin-native
m
what is the idea around handling objc checked exceptions in kotlin native (docs only really mention the opposite situation. E.g. consider AVAudioPlayer, in swift you deal with it like that:
Copy code
do {
    try AVAudioPlayer(contentsOf: url)
} catch {
    // handle exception
}
In Kotlin Native it's signature is
Copy code
public constructor(contentsOfURL: platform.Foundation.NSURL, error: CPointer<ObjCObjectVar<NSError?>>?)
How do you handle error here?
s
Objc makes a distinction between errors and exceptions. Errors are recoverable events whereas exceptions are not. An ObjC exception is thrown and you should only do a little cleanup before exiting the app.
m
Okay, but given the signature of the function above, how do I handle this recoverable error? There's something passed as an argument to the function and it references a potential error when it's thrown, I assume. Right now I just pass null there. What's the right way to handle it?
s
You need to pass a pointer into the function. Wrap it in a memscoped block so that it is automatically reclaimed. Something like this should work.
Copy code
val player: AVAudioPlayer
memScoped {
    val errorPtr: ObjCObjectVar<NSError?> = alloc<ObjCObjectVar<NSError?>>()
    player = AVAudioPlayer(url, errorPtr.ptr)
    println(errorPtr.value) //Will be null if the call succeeds.
}
💯 1
m
Thank you! Do you maybe know a good source of knowledge for this low level memory handling stuff in kotlin native? It's probably easier if you come from C workd
s
Only what comes out of the docs. Some of the example code in the K/N repo is helpful too.
🙏 1