From Xojo Documentation

You are currently browsing the old Xojo documentation site. Please visit the new Xojo documentation site!

Class (inherits from Object)

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

Value fa-lock-32.png

Constructor(obj as Object)


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:

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

If ref.Value <> Nil Then
MessageBox("f is Nil.") // This is shown
End If

See Also

UserGuide:Weak References, UserGuide:Memory Management topics