Python call from Objective-C

I am developing a Python / ObjC application, and I need to call some methods in my Python classes from ObjC. I tried several things without success.

  • How can I call a Python method from Objective-C?
  • My Python classes are created in the Builder interface. How can I call a method from this instance?
+7
python objective-c cocoa
source share
1 answer

Use PyObjC.

It is included in Leopard and later.

>>> from Foundation import * >>> a = NSArray.arrayWithObjects_("a", "b", "c", None) >>> a ( a, b, c ) >>> a[1] 'b' >>> a.objectAtIndex_(1) 'b' >>> type(a) <objective-c class NSCFArray at 0x7fff708bc178> 

It even works with iPython:

 In [1]: from Foundation import * In [2]: a = NSBundle.allFrameworks() In [3]: ?a Type: NSCFArray Base Class: <objective-c class NSCFArray at 0x1002adf40> 

`

To call from Objective-C in Python, the easiest way:

  • declare an abstract superclass in Objective-C that contains the API you want to call

  • create empty method implementations in the @implementation class

  • subclassing a class in Python and providing concrete implementations

  • create a factory method for an abstract superclass that creates specific instances of the subclass

those.

 @interface Abstract : NSObject - (unsigned int) foo: (NSString *) aBar; + newConcrete; @end @implementation Abstract - (unsigned int) foo: (NSString *) aBar { return 42; } + newConcrete { return [[NSClassFromString(@"MyConcrete") new] autorelease]; } @end ..... class Concrete(Abstract): def foo_(self, s): return s.length() ..... x = [Abstract newFoo]; [x foo: @"bar"]; 
+16
source share

All Articles