Support weak references to Objective-C objects (#1531)

This commit is contained in:
SvyatoslavScherbina
2018-04-24 12:32:43 +03:00
committed by GitHub
parent 6dc6ba5137
commit 5f661b20aa
9 changed files with 132 additions and 17 deletions
@@ -1,5 +1,6 @@
import kotlinx.cinterop.*
import objcSmoke.*
import konan.ref.*
import kotlin.test.*
fun main(args: Array<String>) {
@@ -11,6 +12,7 @@ fun main(args: Array<String>) {
fun run() {
testTypeOps()
testConversions()
testWeakRefs()
println(
getSupplier(
@@ -145,6 +147,35 @@ fun testMethodsOfAny(kotlinObject: Any, equalNsObject: NSObject, otherObject: An
assertNotEquals(equalNsObject, otherObject)
}
fun testWeakRefs() {
testWeakReference({ NSObject.new()!! })
createAndAbandonWeakRef(NSObject())
testWeakReference({ NSArray.arrayWithArray(listOf(42)) as NSArray })
}
fun testWeakReference(block: () -> NSObject) {
val ref = autoreleasepool {
createAndTestWeakReference(block)
}
assertNull(ref.get())
}
fun createAndTestWeakReference(block: () -> NSObject): WeakReference<NSObject> {
val ref = createWeakReference(block)
assertNotNull(ref.get())
assertEquals(ref.get()!!.hash(), ref.get()!!.hash())
return ref
}
fun createWeakReference(block: () -> NSObject) = WeakReference(block())
fun createAndAbandonWeakRef(obj: NSObject) {
WeakReference(obj)
}
fun nsArrayOf(vararg elements: Any): NSArray = NSMutableArray().apply {
elements.forEach {
this.addObject(it as ObjCObject)