Class
WeakRef
Description
Allows you to retain a reference to an object without requiring it to stay alive.
Methods
Name |
Parameters |
Returns |
Shared |
---|---|---|---|
obj As Object |
Property descriptions
WeakRef.Value
Value As Object
Returns the target object or Nil if the target no longer exists.
This property is read-only.
Method descriptions
WeakRef.Constructor
Constructor(obj as Object)
Note
Constructors are special methods called when you create an object with the New keyword and pass in the parameters above.
Creates a WeakRef instance.
The target object that you want to retain a reference to after it has been destroyed.
This example creates a weak reference to a SQLiteDatabase object. The property "db As SQLiteDatabase" is a property on the App object.
Var dbRef As WeakRef
' Create Database Object
DB = New SQLiteDatabase
dbRef = New WeakRef(DB)
' Set Database File
DB.DatabaseFile = New FolderItem("MyDatabase.sqlite")
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:
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
Compatibility
All project types on all supported operating systems.
See also
Object parent class; Creating Weak References to objects, How Xojo Manages Memory topics