https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
m

Michal Klimczak

08/03/2021, 4:12 PM
Hint for people who come from android background and try to do shared code for ios. Most of
delegates
in ios are weak. You need to keep a strong reference somewhere for them to not get deallocated unexpectedly. This is even more problematic, because usually the problem doesn't manifest itself on debug build, only release build crash and the stacktrace is rubbish.
This will occasionally fail
Copy code
actual class XMLParser actual constructor(inputStreamWrapper: InputStreamWrapper) {

    private val realParser = NSXMLParser(inputStreamWrapper.inputStream)

    actual fun setDelegatingSaxHandler(handler: PlatformSpecificSaxHandler) {
        realParser.delegate = handler
    }

    actual fun parse() {
        realParser.parse()
    }

}
This one is fine
Copy code
actual class XMLParser actual constructor(inputStreamWrapper: InputStreamWrapper) {

    private val realParser = NSXMLParser(inputStreamWrapper.inputStream)

    private var currentHandler : PlatformSpecificSaxHandler? = null

    actual fun setDelegatingSaxHandler(handler: PlatformSpecificSaxHandler) {
        currentHandler = handler //keep the strong reference
        realParser.delegate = handler
    }

    actual fun parse() {
        realParser.parse()
        currentHandler = null
    }

}