6

我一直在尝试在 Swift 的 Objective-C 中复制通常的方法,用于我正在玩的一个新的 swift 应用程序。

如何在 Objective-C 中执行此操作已被详细记录,您将获得共享的苹果事件管理器和调用方法,以将函数注册为具有事件 idsetEventHandler的事件类的处理程序。kInternetEventClasskAEGetURL

因此,在 swift 中,我试图在一个全新的项目中使用添加到模板 AppDelegate.swift 中的这段代码来做同样的事情:

func applicationWillFinishLaunching(aNotification: NSNotification?) {
    var appleEventManager:NSAppleEventManager = NSAppleEventManager.sharedAppleEventManager()
    appleEventManager.setEventHandler(self, andSelector: "handleGetURLEvent:withReplyEvent:", forEventClass: kInternetEventClass, andEventID: kAEGetURL)
}

func handleGetURLEvent(event: NSAppleEventDescriptor?, replyEvent: NSAppleEventDescriptor?) {
    println("yay");
}

据我所知,这只是标准 Objective-c 调用的语法转换。但是我得到了该方法的forEventClassandEventId参数的类型错误setEventHandler

'NSNumber' is not a subtype of 'AEEventClass'forEventClass论据_

和:

'NSNumber' is not a subtype of 'AEEventId'andEventID论据_

我不确定在这个阶段我做错了什么,因为两者kInternetEventClass都是kAEGetURL苹果定义的常量......当然我不需要将它们的NSNumber类型转换为它们各自所需的类型?如果我是,我不知道怎么做。

4

2 回答 2

15

据我从文档中可以看出,类采用常量并将其转换为正确的类型:

func applicationWillFinishLaunching(aNotification: NSNotification?) {
    var appleEventManager:NSAppleEventManager = NSAppleEventManager.sharedAppleEventManager()
    appleEventManager.setEventHandler(self, andSelector: "handleGetURLEvent:withReplyEvent:", forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}
于 2014-06-06T11:27:58.070 回答
1

我发现从 Xcode 8.2 开始,我需要将 MagerValp 的代码转换为以下代码:

func applicationWillFinishLaunching(_ notification: Notification) {
    let aem = NSAppleEventManager.shared();
    aem.setEventHandler(self, andSelector: Selector(("handleGetURLEvent:withReplyEvent:")), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}

希望这可以帮助。

于 2016-12-25T17:47:23.397 回答