Search code examples
pythonobjective-cpyobjc

Proxing Python class to Objective-C


I try to proxy existing Python class to Objective-C. I started from simple sample of Python class:

Test.py


class Test:
    def __init__(self):
        self.text = ""

    def addText(self, _text):
        self.text = self.text + _text

    def addSomeText(self):
        self.addText("SomeText")

Then I wrote Objective-C class for it.

ITest.h


#import <Cocoa/Cocoa.h>


@interface ITest : NSObject

- (void) addText: (NSString *)text;
- (void) addSomeText;

+ newTest;

@property (nonatomic, assign, getter = _text) NSString *text;

@end

ITest.m


#import "ITest.h"

#define ABSTRACT { return nil; }
#define ABSTRACT_VOID { }


@implementation ITest
@dynamic text;

- (void) addText: (NSString *)text ABSTRACT_VOID;
- (void) addSomeText ABSTRACT_VOID;

+ newTest {
    return [[NSClassFromString(@"TestProxy") new] autorelease];
}

@end

My proxy class (following some articles about PyObjC I subclassing Objective-C class and subclassing original class to access its instance variables):

TestProxy.py


import Foundation
import objc

from Test import Test

ITest = objc.lookUpClass("ITest")

class TestProxy (ITest, Test):
    # getters/setters
    def setText_(self, _text):
        self.text = _text

    def _text(self):
        return self.text

    # methods
    def addText_(self, text):
        Test.addText(self, text)

    def addSomeText(self):
        Test.addSomeText(self)

Now, if I do

ITest *test = [ITest newTest];

I always get nil with no warnings or errors in the debug console.

If I remove all imports and references to original Test class, I'll get working object. I noticed, that nil will be returned exactly as soon as I add from Test import Test.

I think this happens because PyObjC trying to bridge the Test class and fails because its methods do not conform bridge naming rules.

Is there a way to say PyObjC not to do so? Or, maybe, all stuff I did is wrong and there is a better way to translate existing Python stuff to Objective-C?


Solution

  • I just want to make sure that you wrote newText method without return type intentionally.. objective-c methods have its return type most likely, and if you don't want to a specific type to be return use keyword "id".