Search code examples
j2objc

Why doesn't J2ObjC translate field with @Weak as __weak but __unsafe_unretained?


As we know, __unsafe_unretained is not as safe as __weak, so why doesn't J2ObjC translate field with @Weak as __weak but __unsafe_unretained?


Solution

  • Two reasons:

    1. __weak only works in ARC code, and the JRE emulation library is not built with ARC due to a noticeable performance cost.

    2. In Objective C, one can test whether a __weak field has been released by testing whether it's nil. Since there's no way to do that in Java for normal references, code that depends on this behavior is platform-dependent (ie, won't work the same on Android).

    J2ObjC supports the java.lang.reflect package, so if you want a cross-platform way of using weak references, use WeakReference instead of @Weak.