A question came up recently about WeakRefs so I thought I’d post something to help with understanding and using them. I have a longer, more detailed post elsewhere on the forum if you’re interested.
When you create an object, say a Dictionary, divorce in your mind the object from the variable or property that holds it. The object is out there somewhere and the variable is your bridge to it.
dim GoldenGate as new Dictionary
You can assign that object to more than one variable/property, and that creates more bridges, but there is still only one object.
dim GoldenGate as new Dictionary dim Brooklyn as Dictionary = GoldenGate dim Williamsburg as Dictionary = Brooklyn
When there are no more ways to access the object, that is, when all the bridges are gone, the object goes away.
dim GoldenGate as new Dictionary // 1 bridge dim Brooklyn as Dictionary = GoldenGage // 2 bridges GoldenGate = nil // Well, one bridge left Brooklyn = nil // All bridges gone, the object is destroyed
This is known as “reference counting”. When a variable refers to an object, there is a reference and the object sticks around. When there are no more references, the object is destroyed.
But there are times when you want to be able to access an object without creating a reference to it. In other words, you want to be able to test to see if an object still exists, and create a reference to it if it does, without forcing it to stick around. In this example think of it as a string to the object. If there are other bridges to the object, the string will lead you to it too and let you build a bridge. If all the bridges are gone, the string snaps and leads nowhere.
For these times, Xojo has offered the WeakRef. A WeakRef, or weak reference, will let you get to an object without forcing it to stick around in memory if the rest of your code is done with it.
dim d as new Dictionary // the object has one reference dim w as new WeakRef( d ) // still one reference dim d1 as Dictionary = Dictionary( w.Value ) // Now two references d = nil // Back to one reference, w.Value <> Nil d1 = nil // No more references, w.Value = Nil
In the next post, I’ll offer examples of how this is useful.