Managing Objects / WeakRef

I have a class which wraps a class in the Objective C Runtime. I want to maintain the relationship between instances of these two classes in a dictionary, which is a shared property in the Xojo class.

After the Cocoa object is created, the pointer to it is stored as the key and Self as the value in the dictionary. Whenever a Xojo “callback” method is called from the Objective C Runtime (delegate, datasource, overridden method), I can lookup the Xojo object in the dictionary with the Objective C pointer.

Now when the Xojo object is done, the destructor is never called, as there is a reference to it still existing – in the dictionary maintaining the relationship. And as the destructor is never called, I don’t have a place to release the Objective C pointer.

Is the solution to use WeakRef when adding Self as value to the dictionary maintaining the relationship?

I store a weakref and in the callback check that the weakref.value<>nil before doing anything with it.

That’s what I do :slight_smile: unless there’s a natural way to break the cycle. In a Control subclass that has this sorta Shared dispatch I use hard references and break them in the Close event. I try to avoid WeakRefs because of it’s little little more overhead but if there’s no clean/easy/natural way to clean up they’re a perfect fit.