4

私はNSXPCConnection迅速に使用しようとしています。

したがって、この行:

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

次の行に置き換えることができます。

_connectionToService = NSXPCConnection(serviceName: "SampleXPC")

そして、この行:

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

次の行に置き換えることができます。

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

今、私は正しい置換を使用することについて混乱しています: <#Protocol#>in swift、objective cでは: を使用して@protocol(StringModifing)いましたが、swiftでは無知です:(

4

2 に答える 2

2

それはトリッキーなものです。

まず、protocol は予約済みのキーワードであり、パラメーター ラベルとして使用することはできません。Applesの公式ドキュメントをざっと見てみると、ここで役に立ちました。代わりに `protocol`` を使用してください。これは、パラメーター名に一重引用符が含まれていることを意味します。

「[obj クラス]」は、swift で「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 に答える