WeakAddressOf

From Xojo Documentation

Operator

Creates a Delegate, just like AddressOf does, with the difference that it references the method's object instance using a WeakRef internally.

Usage

delegate = WeakAddressOf methodName

Part Description
Delegate A delegate that references methodName. The Delegate automatically converts to a Ptr.
methodName The method to which you want a pointer.

Notes

It can only be used with instance methods of classes, not with shared methods and global methods from modules (use AddressOf for those).

If the delegate method is invoked after the object has been destroyed, an exception will be raised.

WeakAddressOf and AddressOf are operators, not functions, and cannot be used with parentheses. For example, WeakAddressOf(someMethod) leads to an error. Use WeakAddressOf someMethod instead.

Sample Code

This example lets you handle the Timer.Action event without creating a Timer subclass. Start by adding a property to the layout:

MyTimer As Xojo.Core.Timer

Next, add a ProgressBar to the layout. The Timer will simply update the ProgressBar.

In the Open event handler of the layout, instantiate the Timer and indicate that its Action event handler should be handled by a method, TimerAction, that you will add to the layout:

MyTimer = New Xojo.Core.Timer
MyTimer.Period = 1000
MyTimer.Mode = Xojo.Core.Timer.Modes.Multiple

AddHandler MyTimer.Action, WeakAddressOf TimerAction

Now add the TimerAction method to the layout:

Sub TimerAction(sender As Xojo.Core.Timer)
If ProgressBar1.CurrentValue < ProgressBar1.MaxValue Then
ProgressBar1.CurrentValue = ProgressBar1.CurrentValue + 1
Else
' Stop Timer and Remove the handler
sender.Mode = Xojo.Core.Timer.Mode.Off
RemoveHandler MyTimer.Action, WeakAddressOf TimerAction
End If
End Sub

Remember that the first parameter to TimerAction must be of the type of the original object, in this case a Timer. When you run the project, the ProgressBar is updated once per second.

See Also

MemoryBlock function; AddHandler, AddressOf, Declare statement; Delegate, Ptr data types; Operator Precedence.