Main Content

matlab.lang.WeakReference Class

Namespace: matlab.lang

Weak reference to handle object

Since R2024b

Description

Use the matlab.lang.WeakReference class to create a weak reference to a handle object. The handle object can already exist, or you can create an instance of this class with a placeholder handle object. For more information on weak reference behavior in MATLAB®, see Weak Reference Handles.

Creation

Description

wr = matlab.lang.WeakReference creates a weak reference to a handle object. When no argument is specified, the Handle property is set to a handle to a deleted object of type matlab.lang.HandlePlaceholder.

wr = matlab.lang.WeakReference(obj) creates an instance with the Handle property set to a scalar handle object obj.

example

Properties

expand all

Object for which the weak reference is defined, defined as a scalar handle object.

Attributes:

GetAccess
public
SetAccess
immutable

Examples

collapse all

Create a 2-by-3 array of weak reference placeholders by calling createArray with matlab.lang.WeakReference as the class.

weakArray = createArray(2,3,"matlab.lang.WeakReference")
 
weakArray = 

  2×3 WeakReference array with properties:

    Handle

Verify that the Handle property of the array elements is set to a handle to a deleted matlab.lang.HandlePlaceholder object.

weakArray(1,1).Handle
 
ans = 

  handle to deleted HandlePlaceholder

Construct an instance of the TrialData handle class.

classdef TrialData < handle
    properties
        trialNumber string = "A001"
        trialResults double = 0
    end
end
ref = TrialData;

Construct a weak reference to the object ref.

weakref = matlab.lang.WeakReference(ref)
weakref = 

  WeakReference with properties:

    Handle: [1×1 TrialData]

Clear the original reference to the object.

clear("ref")

Access the Handle property of weakref. Because the only remaining reference to the original object is a weak reference, MATLAB deletes the object.

weakref.Handle
ans = 

  handle to deleted TrialData

Version History

Introduced in R2024b