从 Objective-C 类调用 Swift 函数 [英] Call Swift function from Objective-C class

查看:45
本文介绍了从 Objective-C 类调用 Swift 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个旧的 Objective-C 项目,我想调用新的 Swift 函数和对象,我创建了文件-Bridging-Header.h";和-Swift.h"

I have an old Objective-C project and I want to call new Swift function and object, I have create the file "<ProjectName>-Bridging-Header.h" and "<ProjectName>-Swift.h"

对我来说很容易从 Swift 调用函数到 Objective-C,但我有一个反向问题.

was easy for me call the function from Swift to Objective-C but I have a problem for reverse.

所以我创建了一个简单的类System.Swift"

So I have create a simple class "System.Swift"

import Foundation

@objc class System : NSObject {

    @objc func printSome() {
        println("Print line System");
    }
    
}

现在我尝试遵循文档这里<...>-Swift.h 文件里面我写了这个

now I have try to follow the documentation here and inside the <...>-Swift.h file I have write this

@class System;

@interface System : NSObject

-(void)printSome;

@end

并且我已经将它导入到我的 Objective-C 类中.此时,在我的 Objective-C 代码的 Objective C 类(当前为 UIViewController)中,我尝试调用printSome"方法:

and I have import it inside my Objective-C Class. At this point inside my Objective C class (currently UIViewController) of my Objective-C code I have try to call "printSome" method:

- (void)viewDidLoad
{
    [super viewDidLoad];
    System * sis = [[System alloc] init];
    [sis printSome];
    //any additional setup after loading the view from its nib.
}

现在我有以下错误:

架构 i386 的未定义符号:OBJC_CLASS$_System",引用自:ObjectiveC_Class_That_Call_Swift_Object"中的objc-class-ref.o ld:找不到架构i386 clang的符号:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)

Undefined symbols for architecture i386: "OBJC_CLASS$_System", referenced from: objc-class-ref in "ObjectiveC_Class_That_Call_Swift_Object".o ld: symbol(s) not found for architecture i386 clang: error: linker command failed with exit code 1 (use -v to see invocation)

推荐答案

问题已解决,我之前在我的 Objective-C 类中创建并包含了一个新的 .h 文件命名为 -Swift.h 但是,正如我后来发现的,这一步不是必需的,因为编译器创建了不可见的必要文件.

Problem Solved, I previously create and included a new .h file in my Objective-C class named <ProductModuleName>-Swift.h but, as i discovered later, this step is not necessary because the compiler creates the necessary file invisible.

只需在您的类中包含 -Swift.h 就可以了.

Simply include <ProductModuleName>-Swift.h in your class and it should work.

这篇关于从 Objective-C 类调用 Swift 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆