在Swift中,如何调用Objective-C代码?
苹果提到它们可以共存于一个应用程序中,但这是否意味着人们可以在技术上重用Objective-C中创建的旧类,同时在Swift中构建新类?
在Swift中,如何调用Objective-C代码?
苹果提到它们可以共存于一个应用程序中,但这是否意味着人们可以在技术上重用Objective-C中创建的旧类,同时在Swift中构建新类?
当前回答
引用自文档:
Any Objective-C framework (or C library) that’s accessible as a module can be imported directly into Swift. This includes all of the Objective-C system frameworks—such as Foundation, UIKit, and SpriteKit—as well as common C libraries supplied with the system. For example, to import Foundation, simply add this import statement to the top of the Swift file you’re working in: import Foundation This import makes all of the Foundation APIs—including NSDate, NSURL, NSMutableData, and all of their methods, properties, and categories—directly available in Swift.
其他回答
参见Apple的使用Cocoa和Objective-C的Swift指南。本指南涵盖了如何使用Swift中的Objective-C和C代码,反之亦然,并对如何转换项目或在现有项目中混合和匹配Objective-C/C和Swift部分提出了建议。
编译器自动生成调用C函数和Objective-C方法的Swift语法。如文档所示,这个Objective-C:
UITableView *myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
变成了这样的Swift代码:
let myTableView: UITableView = UITableView(frame: CGRectZero, style: .Grouped)
Xcode也可以在运行中进行这种转换——你可以在编辑Swift文件时使用Open quick,并输入Objective-C类名,它会带你到Swift化的类头。(你也可以通过cmd点击Swift文件中的API符号来获得。)iOS 8和OS X v10.10 (Yosemite)开发者库中的所有API参考文档在Objective-C和Swift表单(例如UIView)中都是可见的。
使任何Swift类的NSObject子类也有意义,我更喜欢使用任何Swift类在Objective-C类中看到,如:
@objc(MySwiftClass)
@objcMembers class MySwiftClass {...}
登录的答案工作良好,除了在最新的Swift 5,它给出了一些编译器错误。以下是针对Swift 5开发人员的修复。
斯威夫特5
import Foundation
class MySwiftObject : NSObject {
var someProperty: AnyObject = "Some Initializer Val" as AnyObject
override init() {}
func someFunction(someArg:AnyObject) -> String {
let returnVal = "You sent me \(someArg)"
return returnVal
}
}
使用objective-c的双向方法
1
在Xcode Project中创建bridge-header.h文件 在bridge-Header文件中导入.h文件 在Build设置中设置bridge-Header的路径。 清理项目
2
在项目中创建objective-c文件(它会自动在Build Settings中为您设置路径) 在bridge-Header文件中导入.h文件
现在可以开始了 谢谢
引用自文档:
Any Objective-C framework (or C library) that’s accessible as a module can be imported directly into Swift. This includes all of the Objective-C system frameworks—such as Foundation, UIKit, and SpriteKit—as well as common C libraries supplied with the system. For example, to import Foundation, simply add this import statement to the top of the Swift file you’re working in: import Foundation This import makes all of the Foundation APIs—including NSDate, NSURL, NSMutableData, and all of their methods, properties, and categories—directly available in Swift.