0

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?

Piasy
  • 989
  • 13
  • 35

1 Answers1

2

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.

tball
  • 1,984
  • 11
  • 21
  • Thanks! I thought that Java's `WeakReference` would be translated as `__week`, but find out it uses the translated `java/lang/ref/WeakReference` class. I look into the source of the translated `WeakReference`, but find nothing like `__weak`, how does it work under ARC? (I have cycle reference and must use `weak` to break it) – Piasy Dec 05 '17 at 23:59
  • An __unsafe_unretained annotation resolves a reference cycle, which is why j2objc translates @Weak to it. The only difference __unsafe_unretained and __weak is that the latter also zeros the field when the instance is dealloc'd. That's not a problem for translated code, since when an instance is dealloc'd, the compiler shouldn't allow references to the instance's fields. If you need zeroing field behavior in your code, then use a java.lang.ref.WeakReference. – tball Dec 07 '17 at 01:14
  • Thanks for your answer! I have switched to `java.lang.ref.WeakReference`, but I'm a little bit curious that how does translated `java.lang.ref.WeakReference` work in objc, does it use `__weak` internally? – Piasy Dec 07 '17 at 02:00
  • No, I based on the java.lang.ref support on a great article by Mike Ash: http://mikeash.com/pyblog/friday-qa-2010-07-16-zeroing-weak-references-in-objective-c.html. Here's the support class: https://github.com/google/j2objc/blob/master/jre_emul/Classes/IOSReference.m – tball Dec 07 '17 at 02:50
  • Clang now supports zeroing weak references in non-ARC code, with the `-fobjc-weak` flag. j2objc has been updated to always generate `__weak` annotations instead of `__unsafe_retained` for `@Weak` annotations, and its `j2objcc` script (which sets clang flags) updated to include that flag. – tball Apr 06 '22 at 18:07