Uploaded image for project: 'Swift'
  1. Swift
  2. SR-8878

Using Mirror to access a weak reference results in object being retained indefinitely



    • Type: Bug
    • Status: Resolved
    • Priority: Medium
    • Resolution: Done
    • Component/s: Standard Library
    • Environment:

      Xcode Version 10.0 (10A255)

      Does NOT happen in Xcode 9.4 (9F1027a)


      Please see attached example file "Bug.swift". This file creates an object "WeakHolderObject" which has a weak reference to another object, "AnObject" via the field "weakObject". A Mirror is then used to access the "weakObject" field. All of this is done in an autoreleasepool so that all memory should be released when the pool ends. However, when run in Xcode 10, "AnObject" is not deallocated and is retained indefinitely. Removing the Mirror operation OR running in Xcode 9.4 prevents this problem from occurring.

      An additional trickier effect of this can be seen in "Bug2.swift" which is very similar, but we add a 2nd field "anotherField" to "WeakHolderObject" which is declared after the first field, and try to access that with a mirror instead. This still causes "AnObject" to not be deallocated. However, if you reorder the field declarations so that "anotherField" is declared first, then the problem does not occur.

      This issue causes "Heisenbugs" in which just looking at an object's state can cause memory retention, which then can affect program correctness. In my company's application, we use Mirror to create a state dump when a user reports an issue. As a result of this, the act of reporting a bug can cause more bugs!

      Steps to Reproduce
      Run the attached examples "Bug.swift" and "Bug2.swift" in Xcode10.

      Expected Results
      Both examples should print "Released"

      Actual Results
      Both examples instead print "Retained". As noted above, running these examples in Xcode 9.4 produce expected results.



        1. Bug.swift
          0.4 kB
        2. Bug2.swift
          0.4 kB

          Issue Links



              mikeash Mike Ash
              abrindamour Andrew Brindamour
              0 Vote for this issue
              3 Start watching this issue