WeakRef

From Xojo Documentation

Class (inherits from Object)

Allows you to retain a reference to an object without requiring it to stay alive.

Properties
Value
Constructors

WeakRef.Constructor(obj as Object)


Notes

WeakRef is useful when you want to find out when an object (such as a database or TCP/IP connection) is still in use somewhere in the application. The reference returned by WeakRef goes to Nil as soon as there are no longer any references to the object. This is the signal that you can do any necessary cleanup work.

When the object is destroyed, the WeakRef's value will change to Nil after all ordinary references have been released and the object has been destroyed. Otherwise, the Value property returns the target object.

Sample Code

This code declares an instance of a FolderItem that will go out of scope and have its reference counter decreased. A weak reference is assigned to the FolderItem instance. While the instance is available, its name is displayed. When the instance is removed from memory, the weak reference value become Nil, so you now know there are no more references to it:

Dim ref As WeakRef
If True Then
Dim f As New FolderItem
f.Name = "TestFile.txt"
ref = New WeakRef(f)
If ref.Value <> Nil Then
MsgBox(FolderItem(ref.Value).Name) // This is shown
Else
MsgBox("f is Nil.")
End If
End If

If ref.Value <> Nil Then
MsgBox(FolderItem(ref.Value).Name)
Else
MsgBox("f is Nil.") // This is shown
End If