gcs*_*str 7 python cocoa objective-c
我正在开发一个Python/ObjC应用程序,我需要在ObjC的Python类中调用一些方法.我尝试了几件事没有成功.
bbu*_*bum 16
使用PyObjC.
它包含在Leopard及其后的版本中.
>>> 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>
Run Code Online (Sandbox Code Playgroud)
它甚至适用于iPython:
In [1]: from Foundation import *
In [2]: a = NSBundle.allFrameworks()
In [3]: ?a
Type: NSCFArray
Base Class: <objective-c class NSCFArray at 0x1002adf40>
Run Code Online (Sandbox Code Playgroud)
`
要从Objective-C调用Python,最简单的方法是:
在Objective-C中声明一个包含要调用的API的抽象超类
在类的@implementation中创建方法的存根实现
在Python中对类进行子类化并提供具体实现
在抽象超类上创建一个工厂方法,创建具体的子类实例
即
@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"];
Run Code Online (Sandbox Code Playgroud)