简体   繁体   English

从Swift访问Objective-C变量/函数

[英]Accessing Objective-C variables/functions from Swift

Suppose I have a connector named Connector.m (written in Objective-C). 假设我有一个名为Connector.m的连接器(用Objective-C编写)。 And I would like to create a new connector written using Swift, named Connector.swift. 我想创建一个使用Swift编写的名为Connector.swift的新连接器。 I would like to access all of the variables and methods from Swift. 我想从Swift访问所有变量和方法。 I have create a bridging-header and write import of the header file of the Connector. 我创建了一个桥接头,并写入了连接器头文件的导入。 But I can't access any of global variables on the Objective-C class. 但是我无法访问Objective-C类上的任何全局变量。

Connector.m 连接器

NSString * const kHTTP_METHOD_GET = @"GET";

Connector.swift 连接器

public class Connector: NSObject {

    var parentConnector : Connector

    override init() {
        self.parentConnector = Connector
    }

    func test() {
        print(parentConnector.kHTTP_METHOD_GET) //--> ERROR : Value of type 'Connector' has no member 'kHTTP_METHOD_GET'
    }

}

Is it possible to do this? 是否有可能做到这一点? Thanks. 谢谢。

Add following line in Connector.h. 在Connector.h中添加以下行。

extern NSString * const kHTTP_METHOD_GET;

Include Connector.h to your bridging header file. 将Connector.h包含到桥接头文件中。

Make sure you have header file like this... 确保您有这样的头文件...

{project-name}-Bridging-Header.h

Add your class file in Bridging-Header.h 将您的课程文件添加到Bridging-Header.h中

#import "Connector.h"

And Put your below code in Connector.h file..Because in Bridging-Header.h will only import header file 并将下面的代码放入Connector.h文件中。由于Bridging-Header.h仅导入头文件

NSString * const kHTTP_METHOD_GET = @"GET";

to on top of @interface scope.. 到@interface范围的顶部。

我相信Connector.m中的方法/变量也需要公开才能起作用。

This sounds like a good use-case for the Adapter Pattern . 听起来这是Adapter Pattern的一个很好的用例。 But you should be able to access Objective-C code easily. 但是您应该能够轻松访问Objective-C代码。

Make sure your bridging header file is named like this: 确保您的桥接头文件的命名如下:

{your-project-name}-Bridging-Header.h

Inside your bridging header add the following: 在桥接头中添加以下内容:

#import "Connector.m"

Then you have to make sure the compiler knows about your bridging header: 然后,您必须确保编译器知道您的桥接标头:

Click your root project > Select your target app > Build Settings 单击您的根项目>选择您的目标应用程序>构建设置

Then scroll down until you see this: 然后向下滚动,直到看到以下内容:

在此处输入图片说明

Make sure your bridging header is listed, build and you should have access to your Objective-C code. 确保您的桥接头已列出,构建,并且您应该可以访问Objective-C代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM