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

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

问题描述

我有一个旧的Objective-C项目,我想调用新的Swift函数和对象,我已经创建了文件"<ProjectName>-Bridging-Header.h"和"<ProjectName>-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");
    }
}

现在我已经尝试按照文档

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.old:未为体系结构i386铛找到符号:错误:链接器 命令失败,退出代码为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文件并将其包含在名为<ProductModuleName>-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.

只需在您的班级中加入<ProductModuleName>-Swift.h,它就可以正常工作.

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

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

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