45

If my reading of Mike Ash's "Zeroing Weak References" writeup is correct, weak references are like assign references without ARC. However, if the referenced object is deallocated, instead of getting a "dangling pointer" (meaning a pointer that points to a deallocated object), the pointer gets set to nil.

Is this right, and does this happen with any property marked weak or assign (when ARC is active)?

If this is correct, this would eliminate a lot of SIGABRTs.

Rayfleck
  • 12,116
  • 8
  • 48
  • 74
Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421

1 Answers1

38

It's mostly right, but assign properties are still treated the same as they ever were, only weak ones are zeroing. Another caveat is that zeroing weak references are only available in Mac OS X ≥ 10.7 and iOS ≥ 5. While the rest of ARC was backported to 10.6 and iOS 4, weak references cannot be used at all on these OS's.

cobbal
  • 69,903
  • 20
  • 143
  • 156
  • 6
    Thanks for that @cobbal. At least in XCode 4.2 beta, you CANNOT use `weak` in a property declaration if your deployment target is < iOS 5: you must use `assign`. Message is `error: the current deployment target does not support automated __weak references` – Dan Rosenstark Aug 31 '11 at 14:46
  • 1
    Thank you @Yar, I was getting that error and did not know where it came from! – Pascal Sep 07 '11 at 17:04
  • Doesn't iOS 4 support __unsafe_unretained as a substitute for __weak? – Mark Adams Dec 29 '11 at 17:29
  • 3
    @MarkAdams it does, but as the name implies they are unsafe. When the object a weak references points to is destroyed, the weak reference goes to nil. With unsafe_unretained references, however, the reference points to the same (now deallocated) chunk of memory, and any messages sent to it will likely result in a segfault. – cobbal Dec 29 '11 at 17:39
  • 1
    Further note: Mac OS X 10.6 support is limited to 64-bit apps; 32-bit code uses the legacy runtime and can’t use ARC at all. – Rob Rix Jan 31 '12 at 05:06
  • Note: You can now use __weak with iOS4 and 10.6 by using https://github.com/plausiblelabs/PLWeakCompatibility – Charlie Groves Oct 16 '12 at 16:31
  • Does this also go for `__weak` ivars or just properties? – devios1 Aug 09 '13 at 18:45
  • 1
    @chaiguy yep, a `weak` property just means it uses a `__weak` ivar, so they'll be exactly the same. – cobbal Aug 09 '13 at 19:27