Just My Life & My Work

隨著Swift發展日益盛行,以Objective C為主開發的我要開始與Swift「交互作用」,這次主題是在Objective C使用Swift的Singleton,這看似很容易達成的用法,卻在我又多了C語言來混用,就變得複雜啊~

[iOS] 在Objective C使用Swift的Singleton.png

上圖可理解為:

  • .swfit:可以在Swift使用Objective C。
  • .m:可以在Objective C使用Swift。
  • .mm:可以在Objective C使用C。

原以為可以在.mm中再使用Swift,卻被編譯出其他問題,目前我沒找到可以直接同時使用三種語言的解法,倒是有拐個彎的替代作法如上圖。

Swift 4確認可用:

@objc class CharacteristicViewController : UIViewController {

@objc static let sharedInstance = CharacteristicViewController()

}

@objc func happyPrint() {
print(“Happy Singleton Worked")
}

想要給Objective C使用,記得要加@objc讓編譯器辨識。剛打@objc時,要先按Command+B編譯,接著在Objective C中打關鍵字就會跳出選項,表示編譯器已辨識可以使用。

Objective C部分:

#import “TestPatch-Swift.h"

– (void)viewDidLoad {
[super viewDidLoad];

CharacteristicViewController *characteristicViewController = [CharacteristicViewController sharedInstance];

[characteristicViewController happyPrint];
}

列印出來為:

Happy Singleton Worked

先暫時這麼做吧~

有更好的做法的朋友,請提示我吧:)~

參考:iOS – Can’t access Swift Singleton from Objective-C

 

隨意留個言吧:)~

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料

標籤雲