Cool PyObjC Trick

With PyObjC, you can edit classes at runtime on an ad hoc basis. In particular, you can change what methods a class responds to, both adding and replacing methods in a class with new implementations at will. You can also cache the original implementation and easily invoke it from your replacement implementations.

% python
>>> from Foundation import *
>>> from objc import classAddMethods, classAddMethod
>>> oldDescription = NSObject.instanceMethodForSelector_("description")
>>> def newDescription_(self):
...   print "New %s description" % oldDescription(self)
...
>>> x = NSObject.alloc().init()
>>> x.description()

>>> classAddMethod(NSObject, "description", newDescription_)
>>> x.description()
New <NSObject: 0x379a70> description
>>>

The same can be done in pure ObjC (mostly C, really), but it is a lot harder.



Leave a Reply

Line and paragraph breaks automatic.
XHTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>