Allows you to retain a reference to an object without requiring it to stay alive.
Value As Object
Returns the target object or Nil if the target no longer exists.
This property is read-only.
Constructor(obj as Object)
Creates a WeakRef instance.
The target object that you want to retain a reference to after it has been destroyed.
Var dbRef As WeakRef // Create Database Object DB = New SQLiteDatabase dbRef = New WeakRef(DB) // Set Database File DB.DatabaseFile = New FolderItem("MyDatabase.sqlite")
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.
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 Else MessageBox("f is Nil.") End If End If If ref.Value <> Nil Then MessageBox(FolderItem(ref.Value).Name) Else MessageBox("f is Nil.") // This is shown End If
All project types on all supported operating systems.