Search code examples
pythonobjective-ccocoaappdelegatepyobjc

Implementing NSApplication delegate protocol for openFile in PyObjC


I want to do this in Python (pyobjc)

-(BOOL) application: (NSApplication*)sharedApplication openFile:(NSString*) fileName {
...
}

My delegate is a Python class like this:

class ApplicationDelegate(NSObject):
    ...
    def applicationDidFinishLaunching_(self, notification):
    ...
    def applicationWillTerminate_(self, sender):
    ...

How can I implement NSApplication delegate protocol for openFile in PyObjC?


Solution

  • The Objective-C method name is "application:openFile:", colons included. PyObjC translates ObjC names by replacing colons with underscores. So the method name you need is "application_openFile_":

    class ApplicationDelegate (NSObject):
        def application_openFile_(self, application, fileName):
            pass
    

    Since NSApplicationDelegate is an "informal protocol" and the methods are optional there's no need in Python to declare your conformance. If there were, the protocol would be represented on the Python side by a mixin-style class, and your class definition would look like this:

    class AppDelegate (NSObject, NSApplicationDelegate):
        pass