首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >替换swift中的@protocol(<protocol name>)

替换swift中的@protocol(<protocol name>)
EN

Stack Overflow用户
提问于 2014-10-10 10:26:07
回答 2查看 744关注 0票数 4

我正在尝试在swift中使用NSXPCConnection

所以,这一行:

代码语言:javascript
复制
_connectionToService = [[NSXPCConnection alloc] initWithServiceName:@"SampleXPC"];

可以替换为下面这一行:

代码语言:javascript
复制
_connectionToService = NSXPCConnection(serviceName: "SampleXPC")

并且,这一行:

代码语言:javascript
复制
_connectionToService.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(StringModifing)];

可以替换为下面这一行:

代码语言:javascript
复制
_connectionToService.remoteObjectInterface = NSXPCInterface(protocol: <#Protocol#>)

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

EN

回答 2

Stack Overflow用户

发布于 2015-02-04 20:29:38

这是一个棘手的问题。

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

在swift中,"obj class“正在被"obj.self”所取代。协议也使用相同的语法。这意味着在你的例子中,"@protocol(StringModifing)“变成了"StringModifing.self”。

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

总的来说,解决方案是:

代码语言:javascript
复制
@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
    }
}
票数 2
EN

Stack Overflow用户

发布于 2018-09-17 17:35:14

Swift 4

代码语言:javascript
复制
_connectionToService.remoteObjectInterface = NSXPCInterface(with: StringModifing.self)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26291005

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档