繁体   English   中英

在Objective-C中执行快速代码

[英]Execute swift code in Objective-C

当我在Objective-C中执行Swift方法时,该方法内部的代码将无法运行。

例如:我想打开一个新视图或启用一个按钮。

Objective-C代码:

Principal *myClass = [[Principal alloc] init];
[myClass getData];

SWIFT代码:

func getData() {
    let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let vc: UIViewController = storyboard.instantiateViewControllerWithIdentifier("MenuViewController") as UIViewController
    dispatch_async(dispatch_get_main_queue(), {
        self.presentViewController(vc, animated: true, completion: nil)
    })
}

确保使用@objc关键字标记Swift类,以便ObjC类可以使用它们。

import Foundation

@objc class TestClass {
class func new() -> TestClass {
    return TestClass()
}

func testFunction() {
    println("This function works")
}
}

这是Objective-C客户端:

#import "AppDelegate.h"
#import "TestProject-Swift.h"
@implementation AppDelegate
 - (BOOL)application:(UIApplication *)application 
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    TestClass *instance = [TestClass new];
    [instance testFunction];
    return YES;
}
@end

这里的秘密是在扩展名为“ -Swift.h”的情况下导入目标的名称“ TestProject”。 Xcode为您构建了此代码,并将其隐藏在派生数据的幕后。 对于上面的示例,我的位置为:DerivedData / TestProject-aqpeqeuqusyzdtcqddjdixoppyqn / Build / Intermediates / TestProject.build / Debug-iphoneos / TestProject.build / DerivedSources / TestProject-Swift.h

您需要在项目中创建一个标头(.h文件),然后导入所需的所有类。

您的头文件看起来像。

#ifndef ProjectName_Bridging_Header_h
#define ProjectName_Bridging_Header_h

#import "Principal.h"

在“构建设置”中,需要将头文件名设置为“ Objective-C Bridging Header

像这样。 在此处输入图片说明

暂无
暂无

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

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