Difference between revisions of "WeakRef"

From Xojo Documentation

Line 30: Line 30:
 
   ref = New WeakRef(f)
 
   ref = New WeakRef(f)
 
   If ref.Value <> Nil Then
 
   If ref.Value <> Nil Then
     MsgBox(FolderItem(ref.Value).Name) // This is shown
+
     MessageDialog.Show(FolderItem(ref.Value).Name) // This is shown
 
   Else
 
   Else
     MsgBox("f is Nil.")
+
     MessageDialog.Show("f is Nil.")
 
   End If
 
   End If
 
End If
 
End If
  
 
If ref.Value <> Nil Then
 
If ref.Value <> Nil Then
   MsgBox(FolderItem(ref.Value).Name)
+
   MessageDialog.Show(FolderItem(ref.Value).Name)
 
Else
 
Else
   MsgBox("f is Nil.") // This is shown
+
   MessageDialog.Show("f is Nil.") // This is shown
 
End If
 
End If
 
</rbcode>
 
</rbcode>

Revision as of 21:58, 7 August 2019

Class (inherits from Object)

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

Properties
Value
Constructors

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:

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
MessageDialog.Show(FolderItem(ref.Value).Name) // This is shown
Else
MessageDialog.Show("f is Nil.")
End If
End If

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

See Also

UserGuide:Weak References, UserGuide:Memory Management topics