# Weak reference to object being deallocated

**URL:** <https://forums.swift.org/t/weak-reference-to-object-being-deallocated/38168>\
**Category:** Discussion\
**Created:** [July 4, 2020, 12:23pm UTC](https://forums.swift.org/t/weak-reference-to-object-being-deallocated/38168 "2020-07-04T12:23:17Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Nickolas\_Pohilets](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nickolas_pohilets/32/10659_2.png) [@Nickolas\_Pohilets](https://forums.swift.org/u/Nickolas_Pohilets)\
**Post date:** [July 4, 2020, 12:23pm UTC](https://forums.swift.org/t/weak-reference-to-object-being-deallocated/38168/1 "2020-07-04T12:23:17Z")

</div>

Related to [Hashing Weak Variables](https://forums.swift.org/t/hashing-weak-variables/31345).

I want to create my `WeakRef` for object being deallocated in order to find it among array of `WeakRef`'s and delete it. This works fine for pure Swift classes, but triggers a runtime error for ObjC classes.

Difference in behaviour is confusing, IMO two cases should behave the same way.

And behaviour of the Swift case seems more logical to be - it produces a nil weak reference. Any reasons why the same is not possible for NSObject subclasses?

There is an internal function `objc_initWeakOrNil`  
from [objc-internal.h](https://opensource.apple.com/source/objc4/objc4-706/runtime/objc-internal.h.auto.html) which does what I would expect in this case, but it is not even part of [Objective-C Automatic Reference Counting (ARC) — Clang 16.0.0git documentation](https://clang.llvm.org/docs/AutomaticReferenceCounting.html).

Should Swift runtime use `objc_initWeakOrNil` instead of `objc_initWeak` for consistent behavior of weak references?
