如何从Swift调用Objective-C代码? [英] How do I call Objective-C code from Swift?

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

问题描述

在Swift中,如何调用Objective-C代码?

In Swift, how does one call Objective-C code?

Apple提到它们可以在一个应用程序中共存,但这是否意味着在技术上可以重复使用由Objective-C创建的旧类,同时在Swift中构建新类呢?

Apple mentioned that they could co-exist in one application, but does this mean that one could technically re-use old classes made in Objective-C whilst building new classes in Swift?

推荐答案

在Swift中使用Objective-C类

如果您要使用现有的课程,请执行第2步,然后跳到第5步. (在某些情况下,我必须在旧的Objective-C文件中添加一个显式的#import <Foundation/Foundation.h.)

If you have an existing class that you'd like to use, perform Step 2 and then skip to Step 5. (For some cases, I had to add an explicit #import <Foundation/Foundation.h to an older Objective-C File.)

步骤1:添加Objective-C实现-.m

.m文件添加到您的班级,并将其命名为CustomObject.m.

Step 1: Add Objective-C Implementation -- .m

Add a .m file to your class, and name it CustomObject.m.

添加.m文件时,可能会被如下所示的提示击中:

When adding your .m file, you'll likely be hit with a prompt that looks like this:

点击

如果没有看到提示,或者不小心删除了桥接标题,请在项目中添加一个新的.h文件并将其命名为<#YourProjectName#>-Bridging-Header.h.

If you did not see the prompt, or accidentally deleted your bridging header, add a new .h file to your project and name it <#YourProjectName#>-Bridging-Header.h.

在某些情况下,尤其是在使用Objective-C框架时,您无需显式添加Objective-C类,并且Xcode找不到链接器.在这种情况下,创建如上所述的.h文件,然后确保将其路径链接到目标的项目设置中,如下所示:

In some situations, particularly when working with Objective-C frameworks, you don't add an Objective-C class explicitly and Xcode can't find the linker. In this case, create your .h file named as mentioned above, then make sure you link its path in your target's project settings like so:

注意:

最佳实践是使用$(SRCROOT)宏链接您的项目,以便在移动项目或使用远程存储库与其他项目一起使用时,该项目仍然有效.可以将$(SRCROOT)视为包含.xcodeproj文件的目录.可能看起来像这样:

It's best practice to link your project using the $(SRCROOT) macro so that if you move your project, or work on it with others using a remote repository, it will still work. $(SRCROOT) can be thought of as the directory that contains your .xcodeproj file. It might look like this:

$(SRCROOT)/Folder/Folder/<#YourProjectName#>-Bridging-Header.h

步骤3:添加Objective-C标头-.h

添加另一个.h文件并将其命名为CustomObject.h.

Step 3: Add Objective-C Header -- .h

Add another .h file and name it CustomObject.h.

CustomObject.h

#import <Foundation/Foundation.h>

@interface CustomObject : NSObject

@property (strong, nonatomic) id someProperty;

- (void) someMethod;

@end

CustomObject.m

#import "CustomObject.h"

@implementation CustomObject 

- (void) someMethod {
    NSLog(@"SomeMethod Ran");
}

@end

第5步:将类添加到Bridging-Header

YourProject-Bridging-Header.h中:

#import "CustomObject.h"

第6步:使用您的对象

SomeSwiftFile.swift中:

var instanceOfCustomObject = CustomObject()
instanceOfCustomObject.someProperty = "Hello World"
print(instanceOfCustomObject.someProperty)
instanceOfCustomObject.someMethod()

无需显式导入;这就是桥接头的作用.

There is no need to import explicitly; that's what the bridging header is for.

.swift文件添加到您的项目中,并将其命名为MySwiftObject.swift.

Add a .swift file to your project, and name it MySwiftObject.swift.

MySwiftObject.swift中:

import Foundation

@objc(MySwiftObject)
class MySwiftObject : NSObject {

    @objc
    var someProperty: AnyObject = "Some Initializer Val" as NSString

    init() {}

    @objc
    func someFunction(someArg: Any) -> NSString {
        return "You sent me \(someArg)"
    }
}

步骤2:将Swift文件导入ObjC类

SomeRandomClass.m中:

#import "<#YourProjectName#>-Swift.h"

即使您看不到文件,<#YourProjectName#>-Swift.h文件也应该已经在您的项目中自动创建.

The file:<#YourProjectName#>-Swift.h should already be created automatically in your project, even if you can not see it.

MySwiftObject * myOb = [MySwiftObject new];
NSLog(@"MyOb.someProperty: %@", myOb.someProperty);
myOb.someProperty = @"Hello World";
NSLog(@"MyOb.someProperty: %@", myOb.someProperty);

NSString * retString = [myOb someFunctionWithSomeArg:@"Arg"];

NSLog(@"RetString: %@", retString);

注意:

  1. 如果代码完成不如您预期的那样,请尝试使用 R 运行快速构建以帮助Xcode从Swift上下文中找到一些Objective-C代码,反之亦然.

  1. If Code Completion isn't behaving as you expect, try running a quick build with R to help Xcode find some of the Objective-C code from a Swift context and vice versa.

如果将.swift文件添加到较旧的项目中并出现错误dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib,请完全尝试重新启动Xcode .

If you add a .swift file to an older project and get the error dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib, try completely restarting Xcode.

虽然最初可以使用通过@objc前缀对Objective-C可见的纯Swift类(不是NSObject的后代),但这不再是可能的.现在,要在Objective-C中可见,Swift对象必须是符合NSObjectProtocol的类(最简单的方法是从NSObject继承),或成为带有enum并标记为@objc的对象某些整数类型(如Int)的原始值. 您可以使用@objc在没有这些限制的情况下查看Swift 1.x代码示例的编辑历史记录.

While it was originally possible to use pure Swift classes (Not descendents of NSObject) which are visible to Objective-C by using the @objc prefix, this is no longer possible. Now, to be visible in Objective-C, the Swift object must either be a class conforming to NSObjectProtocol (easiest way to do this is to inherit from NSObject), or to be an enum marked @objc with a raw value of some integer type like Int. You may view the edit history for an example of Swift 1.x code using @objc without these restrictions.

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

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