2014-10-10 68 views
3

我試圖在swift中使用NSXPCConnection在swift中替換@protocol(<protocol name>)

所以,這條線:

_connectionToService = NSXPCConnection(serviceName: "SampleXPC") 

而且,這條線:

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

可以通過這條線所取代:

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

可以通過這條線來代替

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

現在我感到困惑使用正確的更換:在迅速<#Protocol#>,在目標C我會用:@protocol(StringModifing),但在迅疾我無言以對:(

+2

嘗試'StringModifing.self'。 – dasblinkenlight 2014-10-10 02:34:08

回答

0

這是一個棘手的一個。

首先,協議是保留關鍵字,不能用作參數標籤。蘋果官方文檔的快速瀏覽幫助我在這裏。使用`protocol``來代替。這意味着參數名稱包含單引號。

「[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 
    } 
} 
相關問題