What is the recommended way to call APIs that have...
# ios
j
What is the recommended way to call APIs that have a
NSError **
argument?
j
The general pattern is something like:
Copy code
memScoped {
    val error = alloc<ObjCObjectVar<NSError?>>()
    val result = objcFun(params, error.ptr)
    val nsError = error.value
    if (nsError != null) {
        // throw exception, return error type, etc.
    }
    // return result, success type, etc.
}
You can wrap this code in a reusable function that aligns with your app's error handling pattern.
Note, I've also found if you are using Objective-C optional constructors, that may return
nil
on error, since Kotlin constructors can't have
null
return types the interop header can't represent the constructor with a nullable type, and so it will throw a
NullPointerException
when an error occurs. In this case I catch the NPE and handle the
NSError
instead.
j
That’s helpful, thanks!
I found this example elsewhere on the web. Is yours substantially different from this?
Copy code
val nsError: NSError? = null
val errorPtr = ObjCObjectVar<NSError?>(nsError.objcPtr()).ptr
j
Have you tried this code? It won't compile. Native memory has to be allocated on the heap:
alloc<ObjCObjectVar<NSError?>>()
j
No, it seems to not give errors in the IDE but I am still working on the tests.
I suppose my question is, is yours just heap allocated and “mine” is on the stack? Or is getting stack pointers in Kotlin just unsupported?
Lol okay it doesn’t compile
j
There are occasional subtle differences between the IDE and the compiler with KMP that still need to be ironed out.