I'm getting the message `Native interop types cons...
# kotlin-native
s
I'm getting the message
Native interop types constructors must not be called directly
when compiling this bit of code:
Copy code
val nsError: NSError? = null
    val nsErrorPtr = ObjCObjectVar<NSError?>(nsError.objcPtr()).ptr
    val decoder = NSKeyedUnarchiver(forReadingFromData = data, error = nsErrorPtr) //Error is generated by this line.
This should be a valid constructor but it is throwing that compiler error.
b
There's usually a matching class method you can call instead like unarchiverForReading…
s
There are only methods for decoding full objects. The object I'm trying to encode and decode an object that doesn't conform to NSCoding. I was planning to encode and decode the fields individually.
🤔 1
I ended up using an old wrapping trick. I put an object into a container that conforms to NSCoding and then did the encoding/decoding work there.
Copy code
class AuthTokenContainer(val authToken: AuthToken) : NSObject(), NSCodingProtocol {
    override fun encodeWithCoder(coder: NSCoder) {
         //Several encoding method calls
    }

    override fun initWithCoder(coder: NSCoder): NSCodingProtocol? {
        //coder.decodeXXX methods omitted
        val authToken = AuthToken(access, scope, expires, identification, refresh)
        return AuthTokenContainer(authToken)
    }
}
The code to decode isn't too bad.
Copy code
val data = NSData.create(base64EncodedString = dataString, options = NSDataBase64Encoding64CharacterLineLength)
        ?: return null

    return when (val container = NSKeyedUnarchiver.unarchiveObjectWithData(data)) {
        is AuthTokenContainer -> {
            container.authToken
        }
        else -> null
    }