Swift專案中呼叫Objective-C的庫
這是來自stack overflow上的一個回答,更多回答請檢視:
http://stackoverflow.com/questions/24002369/how-to-call-objective-c-code-from-swift
Using Objective-C Classes in 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 ObjC File) **
Step 1: Add Objective-C Implementation -- .m
Add a .m file to your class, and name it CustomObject.m
Step 2: Add Bridging Header
When adding your .m file, you'll likely be hit with a prompt that looks like this:
Click YES !
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
In some situations, particularly when working with ObjC 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:
Note
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 repo, 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
Step 3: Add Objective-C Header -- .h
Add another .h file and name it CustomObject.h
Step 4: Build your Objective-C Class
In CustomObject.h
import <Foundation/Foundation.h>
@interface CustomObject : NSObject
@property (strong, nonatomic) id someProperty;
- (void) someMethod;
@end
In CustomObject.m
import "CustomObject.h"
@implementation CustomObject
- (void) someMethod {
NSLog(@"SomeMethod Ran");
}
@end
Step 5: Add Class to Bridging-Header
In YourProject-Bridging-Header.h:
import "CustomObject.h"
Step 6: Use your Object
In SomeSwiftFile.swift:
var instanceOfCustomObject: CustomObject = CustomObject()
instanceOfCustomObject.someProperty = "Hello World"
println(instanceOfCustomObject.someProperty)
instanceOfCustomObject.someMethod()
No need to import explicitly, that's what the bridging header is for.
Using Swift Classes in Objective-C
Step 1: Create New Swift Class
Add a .swift file to your project, and name it MySwiftObject.swift
In MySwiftObject.swift:
import Foundation
class MySwiftObject : NSObject {
var someProperty: AnyObject = "Some Initializer Val"
init() {}
func someFunction(someArg:AnyObject) -> String {
var returnVal = "You sent me \(someArg)"
return returnVal
}
}
Step 2: Import Swift Files to ObjC Class
In SomeRandomClass.m:
import "<#YourProjectName#>-Swift.h"
The file:<#YourProjectName#>-Swift.h should already be created automatically in your project, even if you can not see it.
Step 3: Use your class
MySwiftObject * myOb = [MySwiftObject new];
NSLog(@"MyOb.someProperty: %@", myOb.someProperty);
myOb.someProperty = @"Hello World";
NSLog(@"MyOb.someProperty: %@", myOb.someProperty);
NSString * retString = [myOb someFunction:@"Arg"];
NSLog(@"RetString: %@", retString);
Using PURE Swift Classes in Objective-C
As pointed out by @TomášLinhart in the comments, "To be accessible and usable in Objective-C, a Swift class must be a descendant of an Objective-C class or it must be marked @objc." Because our first example is a descendant of NSObject, the compiler does this automatically. Let's look at an example class that is not a descendant of an Objective-C Class.
Step 1: Create New Swift Class
Add a .swift file to your project, and name it PureSwiftObject.swift
In PureSwiftObject.swift:
import Foundation
// Note '@objc' prefix
@objc class PureSwiftObject {
var name: String
init(name: String) {
self.name = name
}
// Needed to add a class level initializer
class func newInstanceNamed(name: String) -> PureSwiftObject {
return PureSwiftObject(name: name)
}
// Just a method for demonstration
func someMethod() {
println("Some method ran in pure swift object")
}
}
For this, I create a class initializer called 'newInstanceNamed:'. Because this class is no longer a descendent of NSObject, it no longer has access to 'alloc' or 'new'. Perhaps there is another workaround, but this is the only way that I have found. I didn't find any explicit mention of this in the docs. If you do, and it contradicts my approach, please tell me and I'll update the answer to conform to the suggested style.
Step 2: Import Swift Files to ObjC Class
In SomeRandomClass.m:
import "<#YourProjectName#>-Swift.h"
(if you haven't already done so)
Step 3: Use your pure swift class
PureSwiftObject * pureSwiftObject = [PureSwiftObject newInstanceNamed:@"Janet"];
NSLog(@"PureSwiftNamed: %@", pureSwiftObject.name);
[pureSwiftObject someMethod];
Note:
CodeCompletion wasn't behaving as accurately as I'd like it to. On my system, running a quick build w/ "cmd + r" seemed to help Swift find some of the Objc code and vice versa.
If you add .swift file to an older project and get error: dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib, try completely restarting Xcode.
相關文章
- Swift 呼叫 Objective-C 的可變引數函式SwiftObject函式
- Objective-C和Swift混編ObjectSwift
- 專案常用第三方庫 Swift版Swift
- Swift 專案的模組化Swift
- [譯] 輕鬆管理 Swift 專案中的不同環境Swift
- oc與swift檔案的相互呼叫方式——橋接Swift橋接
- XCode 中 Swift / Objective-C / C / C++ 混合程式設計XCodeSwiftObjectC++程式設計
- 純Swift專案-序篇Swift
- 在iOS-Swift專案中整合CppJieba分詞iOSSwiftJieba分詞
- 專案中的公共方法呼叫原則及呼叫的前置條件判斷
- (轉)OC專案轉Swift指南Swift
- Swift原始碼專案編譯Swift原始碼編譯
- Sql Server 資料庫中呼叫dll檔案的過程SQLServer資料庫
- OC 與 Swift 相互呼叫Swift
- 一個在 Objective-C 和 Swift 中實現剖面導向程式設計的故事ObjectSwift程式設計
- flutter中呼叫C++的庫FlutterC++
- 純Swift專案-JSON(Basic.frameworks)SwiftJSONFramework
- Objective-C中的CopyObject
- Swift 檔案快取--DDGDataCache_Swift庫高階封裝用法Swift快取封裝
- OC與Swift混編專案遷移到Swift4.2小記Swift
- Swift 專案總結 01 Swift 反射應用於模型歸檔Swift反射模型
- 一份非常詳盡的 Objective-C 到 Swift 的遷移指南ObjectSwift
- Swift 開源專案精選導圖Swift
- 由專案需求中引出的思考,Promise鏈式呼叫如何防抖Promise
- 來一次有側重點的區分Swift與Objective-CSwiftObject
- 關於一個java專案呼叫另一個java專案的心得Java
- swift-bridge支援從Swift呼叫非同步Rust函式Swift非同步Rust函式
- Swift + RxSwift MVVM 模組化專案實踐SwiftMVVM
- 純Swift專案-Xib | StoryBoard 多人協作技巧Swift
- Swift 專案總結 02 常用分類方法Swift
- VS中呼叫DLL動態庫的方法
- COPR 倉庫中 4 個很酷的新專案(2019.8)
- COPR 倉庫中 4 個很酷的新專案(2019.10)
- COPR 倉庫中 4 個很酷的新專案(2020.01)
- 關於 fontawesome 庫在 Spartacus 專案中的應用
- Swift 中的 @autoclosureSwift
- Swift中的反射Swift反射
- Android專案中獨立Git專案分庫後的編譯除錯時Gradle的配置AndroidGit編譯除錯Gradle
- java中呼叫dll檔案的步驟Java