在 Swift 中,如何调用 Objective-C 代码?
Apple 提到它们可以在一个应用程序中共存,但这是否意味着在技术上可以重用在 Objective-C 中创建的旧类,同时在 Swift 中构建新类?
最佳答案
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.)
添加 .m
文件到您的类(class),并将其命名为 CustomObject.m
.
添加您的.m
时文件,您可能会遇到如下提示:
点击是!
如果您没有看到提示,或者不小心删除了桥接头,请添加新的 .h
将文件添加到您的项目中并将其命名为 <#YourProjectName#>-Bridging-Header.h
.
在某些情况下,特别是在使用 Objective-C 框架时,您没有显式添加 Objective-C 类,Xcode 找不到链接器。在这种情况下,创建您的 .h
如上所述命名的文件,然后确保将其路径链接到目标的项目设置中,如下所示:
注意:
最好使用 $(SRCROOT)
链接您的项目。宏,这样如果你移动你的项目,或者使用远程存储库与其他人一起工作,它仍然可以工作。 $(SRCROOT)
可以认为是包含您的 .xcodeproj 文件的目录。它可能看起来像这样:
$(SRCROOT)/Folder/Folder/<#YourProjectName#>-Bridging-Header.h
添加另一个 .h
文件并将其命名为 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
在 YourProject-Bridging-Header.h
:
#import "CustomObject.h"
在 SomeSwiftFile.swift
:
var instanceOfCustomObject = CustomObject()
instanceOfCustomObject.someProperty = "Hello World"
print(instanceOfCustomObject.someProperty)
instanceOfCustomObject.someMethod()
无需显式导入;这就是桥接头的用途。
添加 .swift
将文件添加到您的项目中,并将其命名为 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)"
}
}
在 SomeRandomClass.m
:
#import "<#YourProjectName#>-Swift.h"
文件:<#YourProjectName#>-Swift.h
应该已经在您的项目中自动创建,即使您看不到它。
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);
如果代码完成没有按预期运行,请尝试使用 ⌘⇧R 运行快速构建以帮助 Xcode从 Swift 上下文中找到一些 Objective-C 代码,反之亦然。
如果添加 .swift
文件到旧项目并得到错误dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib
, 完全尝试restarting Xcode .
虽然最初可以使用纯 Swift 类(不是 NSObject
的后代),但通过使用 @objc
对 Objective-C 可见。前缀,这不再可能。现在,要在 Objective-C 中可见,Swift 对象必须是符合 NSObjectProtocol
的类。 (最简单的方法是从 NSObject
继承),或者成为 enum
标记为 @objc
具有某种整数类型的原始值,例如 Int
. You may view the edit history for an example of Swift 1.x code using @objc
without these restrictions.
https://stackoverflow.com/questions/24002369/