« MBS Filemaker Plugin,… | Home | Toolbar functions for… »

Tip of the day: Weak Property pattern

Often we have to keep properties with references to other objects, but want to avoid circle references causing memory leaks. So we have to have a clear reference tree from root object to child objects. If we want a reference from child back to parent, we need to use a weak reference.

Other use is if you have two windows where one window needs to reference other, but one of the windows should be able to get away without leaving a reference to a dead window. Sometimes we have trouble as a window was closed already, but we have a reference to it. Accessing it causes an exception as controls are dead already.

So how to make a weak property?

First you create the normal property, e.g. test as window. Next you select it to convert it to computed property. The private property created by Xojo now changes type to WeakRef. The setter changes to this:

Sub Set() if value = nil then mTest = nil else mTest = new WeakRef(value) end if End

As you see we now create a weak Reference for the given value. If value is nil, we don't need the weak reference, so we set to nil.
For the getter, we simply take the value from WeakRef the value and return it. We use a variant for easy casting:

Sub Get() if mTest <>Nil then dim v as Variant = mTest.Value return v end if End

The property can now be used like other properties. You don't really notice it is using a weak reference. Just you have to prepare for the case the property is suddenly nil.
26 08 14 - 22:37
No comments

Remember personal info?

Emoticons / Textile

Hide email:

Small print: All html tags except <b> and <i> will be removed from your comment. You can make links by just typing the url or mail-address.