Re: [Pyobjc-dev] NibLoader.py: parsing nibs at runtime
Brought to you by:
ronaldoussoren
From: <bb...@ma...> - 2002-11-16 23:17:48
|
On Saturday, November 16, 2002, at 05:45 PM, Just van Rossum wrote: > Ok, things are getting somewhat clearer, thanks! (But now I'm > wondering who's > setting these ivars: is it Cocoa or the Py/Obj-C bridge?) Ronald can answer with specifics.... In general, the declaration of an iVar in ObjC, whether done programmatically or in the @interface, creates a slot in the instances of that class into which the iVar's value can be stored. Sounds complex? It isn't -- just think of an instance of a class as a big C structure. Subclassing is done by simply unioning the parent classes with the child. The ObjC runtime provides API for getting and setting the values within an instance structure directly. With the lack of a -set*: style method, this is exactly what the IB connection mechanism does. And these are the exact methods that the ObjC bridge uses. See instance-var.m. ... if (strcmp(var->ivar_type, "@") == 0) { object_setInstanceVariable(objc, self->name, *(id*)buf); } else { object_setInstanceVariable(objc, self->name, *(void**)buf); } ... As long as you explicitly declare a class attribute to be an ivar it'll work like an ivar. valueForKey: and takeValue:forKey: are a part of the very cool NSKeyValueCoding protocol found in the Foundation. Like any instance of a python class can be treated as dictionaries and the values can be accessed directly [oversimplification, I know], NSKeyValueCoding allows the same to be done to ObjC classes. An example (first declaration shows what happens when you don't declare the class attribute as a true iVar... and, I know, the semantics are very different between bar-as-a-python-class-attribute and bar-as-an-objc-instance-variable. >>> from Foundation import * >>> class Foo(NSObject): ... bar = 1 ... def foo(self): return self.bar ... >>> x = Foo.alloc().init() >>> x.foo <bound method Foo.foo of <Foo objective-c instance 0xc98990>> >>> x.bar 1 >>> x.bar = 2 >>> x.bar 2 >>> x.foo() 2 >>> x.valueForKey_("foo") Traceback (most recent call last): File "<stdin>", line 1, in ? objc.error: NSUnknownKeyException - [<Foo 0xc98990> valueForKey:]: lookup of unknown key: 'foo'. This class does not have an instance varia >>> from objc import * >>> class Bar(NSObject): ... bar = ivar('bar') ... >>> x = Bar.alloc().init() >>> x.bar >>> x.bar = 1 >>> x.bar 1 >>> x.valueForKey_('bar') 1 |