简体   繁体   English

是否可以从同一项目的Swift类调用目标C应用程序委托方法?

[英]Is it possible to call objective C application delegate method from Swift class of the same project?

I'm merging my Swift project with already existing Objective-C code. 我正在将Swift项目与已经存在的Objective-C代码合并。 I need to call some important methods of Swift class from objective C app delegate. 我需要从目标C应用程序委托中调用Swift类的一些重要方法。 I tried all methods given in net, but it was no use. 我尝试了net中给出的所有方法,但是没有用。 Can any one help me out? 谁能帮我吗?

Yes, it's possible but with some limitations. 是的,有可能,但有一些限制。

You can use only classes which inherited from NSObject, with public attribute and marked with @objc. 您只能使用从NSObject继承的具有公共属性并标有@objc的类。 At Objective-C code you should import "ProductModuleName-Swift.h" file which generated by compiler. 在Objective-C代码中,应导入由编译器生成的“ ProductModuleName-Swift.h”文件。

Here is an example of Swift class: 这是Swift类的示例:

import Foundation

@objc public class ExampleClass: NSObject {
    @objc public var someInstanceProperty = "Property"

    @objc public func someFunction() {
        print("Some function")
    }
}

Notice that this class inherited from NSObject and have @objc and public attributes. 请注意,该类继承自NSObject,并具有@objc和public属性。 After command+B you can take a look at generated bridge header through Assistance editor: 在command + B之后,您可以通过Assistance编辑器查看生成的网桥头: 桥头

Then you should import the bridge header at your Objective-C class. 然后,您应该在Objective-C类中导入桥头。

#import "ProductModuleName-Swift.h"

And then you can use your Swift class at Objective-C code like any other Objective-C class: 然后,您可以像其他任何Objective-C类一样在Objective-C代码中使用Swift类:

__auto_type const someClass = [ExampleClass new];
[someClass someFunction];
NSLog(@"%@", someClass.someInstanceProperty);

Here is an additional information from Apple: Importing Swift into Objective-C 这是来自Apple的其他信息: 将Swift导入Objective-C

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

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