4

我正在尝试NSXPCConnection快速使用。

所以,这一行:

_connectionToService = [[NSXPCConnection alloc] initWithServiceName:@"SampleXPC"];

可以用这一行代替:

_connectionToService = NSXPCConnection(serviceName: "SampleXPC")

而且,这一行:

_connectionToService.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(StringModifing)];

可以用这一行代替:

_connectionToService.remoteObjectInterface = NSXPCInterface(protocol: <#Protocol#>)

现在我对使用正确的替代品感到困惑:<#Protocol#>在swift中,在objective c中我会使用: @protocol(StringModifing),但在swift中我一无所知:(

4

2 回答 2

2

这是一个棘手的问题。

首先protocol是一个保留关键字,不能作为参数标签。快速浏览一下 Apples 官方文档对我有帮助。改用“协议”。这意味着参数名称包含单引号。

“[obj class]”正在迅速被“obj.self”取代。相同的语法用于协议。这意味着在您的情况下“@protocol(StringModifing)”变为“StringModifing.self”。

不幸的是,这仍然行不通。现在的问题在幕后。xpc 机制是某种低级的东西,需要 ObjC 风格的协议。这意味着您需要在协议声明前使用关键字 @objc。

总之,解决方案是:

@objc protocol StringModifing {

    func yourProtocolFunction()
}

@objc protocol StringModifingResponse {

    func yourProtocolFunctionWhichIsBeingCalledHere()
}

@objc class YourXPCClass: NSObject, StringModifingResponse, NSXPCListenerDelegate {

    var xpcConnection:NSXPCConnection!
    private func initXpcComponent() {

        // Create a connection to our fetch-service and ask it to download for us.
        let fetchServiceConnection = NSXPCConnection(serviceName: "com.company.product.xpcservicename")

        // The fetch-service will implement the 'remote' protocol.
        fetchServiceConnection.remoteObjectInterface = NSXPCInterface(`protocol`: StringModifing.self)


        // This object will implement the 'StringModifingResponse' protocol, so the Fetcher can report progress back and we can display it to the user.
        fetchServiceConnection.exportedInterface = NSXPCInterface(`protocol`: StringModifingResponse.self)
        fetchServiceConnection.exportedObject = self

        self.xpcConnection = fetchServiceConnection

        fetchServiceConnection.resume()

        // and now start the service by calling the first function
        fetchServiceConnection.remoteObjectProxy.yourProtocolFunction()
    }

    func yourProtocolFunctionWhichIsBeingCalledHere() {

        // This function is being called remotely
    }
}
于 2015-02-04T12:29:38.097 回答
0

斯威夫特 4

_connectionToService.remoteObjectInterface = NSXPCInterface(with: StringModifing.self)
于 2018-09-17T09:35:13.553 回答