Re: [Pyobjc-dev] weakref-like behavior on ObjC subclasses
Brought to you by:
ronaldoussoren
|
From: Ronald O. <ron...@ma...> - 2008-02-26 15:59:01
|
On 26 Feb, 2008, at 0:26, James R Eagan wrote: > I have a class that implements an observer pattern in python. > Observables maintain weakrefs to listeners that have been registered > with them such that, when a listener goes out of scope, the > observable doesn't keep it alive. Of course, this mechanism fails > as soon as a listener inherits from an ObjC class because weakref > doesn't support ObjC classes. > > At this point, my workaround is to store a strong reference if the > listener can't be weakref'd. I'm not happy about this solution > because it now creates different behaviors depending on whether the > object can be weakref'd. If it can, then the listener is > automatically unregistered from the observable when its lifespan is > up. If it can't, however, then the object must be manually > unregistered before deletion will ever occur. > > This is where the problem arises in PyObjC. Is there any mechanism > through which I can approximate a weak reference to an ObjC object > in Python? Not that I know of. PyObjC explicitly disables weakref support for Objective-C classes because it is AFAIK impossible to get the semantics right. This is due to (lack of) interaction between the Python and Objective-C memory managers, which makes it impossible to keep the weakref valid until the last strong reference to an object goes away, even when that last reference is in Objective-C. There's currently some talk on python-dev about making 'weakref.ref' a generic function (like "len()"), which would allow us to implement a custom weakref type for Objective-C objects. I haven't put much thought into that yet, Cocoa might not have enough hooks to be able to implement such a weakref type. > > > I tried doing some magic by checking the retainCount() of my > objects, but that seems to always be the same, no matter how many > Python objects hold a ref to the ObjC instance. That's right, the Python proxy to an Objective-C object retains the Objective-C object, all references from Python share a single Python proxy object (and use Python's refcounting to decide when that proxy object should die). Ronald |