简体   繁体   English

导出Swift框架以用于Objective-C

[英]Export Swift framework for the usage in Objective-C

I am creating a framework using Swift to be used in my college's Objective-C Project. 我正在使用Swift创建一个框架,以用于我的大学的Objective-C项目。 I have created a new project and have chosen Cocoa Touch Framework and named it printFramework . 我创建了一个新项目,并选择了Cocoa Touch Framework并将其命名为printFramework I have added a Swift file into the project with the code below: 我已使用以下代码将Swift文件添加到项目中:

import Foundation


@objc public class printClass : NSObject {
    @objc public override init() {
        print("My name is init")
    }

    @objc public func printMe(){
        print("Hello Wrold")
    }
}

I build the above code (Build Success) with the target Generic iOS Device , and now I have a briefcase (framework) file and under Product, and I create another Single View Application project with language Objective-C named prinFrameTest . 我使用目标Generic iOS设备构建了上面的代码(构建成功),现在我有了一个公文包(框架)文件,并且在Product下,并且使用Objective-C语言创建了一个名为prinFrameTest的 单视图应用程序项目。 I copied the framework into the project and in General tab under Linked Frameworks and Libraries , I have my printFramwork and above that in Embedded Binaries I have added my printFramework . 我将框架复制到项目中,在“ 链接的框架和库”下的“ 常规”选项卡中,我有我的printFramwork ,在“ 嵌入式二进制文件”中的上面,我添加了我的printFramework

In my ViewController.m I have the following code: 在我的ViewController.m我有以下代码:

#import "ViewController.h"
@import printFramework;
#import <printFramework/printFramework-Swift.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    printClass *pr;
    [pr printMe];
}

@end

I build and run this (it ran successfully), Simulator opens and but the code is not working (means it does not print anything in the log). 我构建并运行了它(它成功运行了),模拟器打开了,但是代码不起作用(意味着它在日志中不打印任何内容)。

What is going wrong? 怎么了?

If you put a breakpoint on the line [pr printMe] and inspect the value of pr , you'll probably see that it's a null reference - you haven't created the object, you've just allocated a variable which can hold a reference to an instance of printClass . 如果您在[pr printMe]行上放置一个断点并检查pr的值,您可能会发现它是一个空引用-您尚未创建该对象,只是分配了一个可以保存引用的变量到printClass的实例。 Try this way: 尝试这种方式:

[[printClass new] printMe];
  1. You need to use [[YourClass alloc] init] to make it work 您需要使用[[YourClass alloc] init]使其起作用
  2. in Xcode project, you need to enable Always embed Swift standard libraries 在Xcode项目中,您需要启用Always embed Swift standard libraries
  3. Building with Generic iOS Device does not produce a universal framework 使用Generic iOS Device构建不会产生通用框架

You need to create a non nil object either 您需要创建一个非nil对象

printClass *pr = [printClass new];

OR 要么

printClass *pr = [[printClass alloc] init];

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

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