2016-11-08 66 views
1

我一直在尋找爲什麼Objective-C類中的singleton方法定義在Xcode的Swift接口上不可用的原因的文檔。Objective C Singleton方法不適用於Swift接口

的Objective-C類的定義如下

/** 
* A general accessor across the sample App to remove the dependency of QPSLibraryManager from resusable components. 
*/ 
@interface QPSSharedAccessor : NSObject 

/** 
* Required by QPSLibraryManager and some UI components. 
*/ 
@property (nonatomic, strong) QPSApplicationConfiguration *qpsConfiguration; 

/** 
* Provides Commands to app 
*/ 
@property (nonatomic, strong) id<QPSAppController> appController;; 

/** 
* Shared singleton. 
*/ 
+ (instancetype)sharedAccessor; 

/** 
* Returns access to a configuration manager 
*/ 
- (QPSConfigurationManager *)configurationManager; 

@end 

在夫特接口,其像這樣

/** 
* A general accessor across the sample App to remove the dependency of QPSLibraryManager from resusable components. 
*/ 
open class QPSSharedAccessor : NSObject { 


    /** 
    * Required by QPSLibraryManager and some UI components. 
    */ 
    open var qpsConfiguration: QPSApplicationConfiguration! 


    /** 
    * Provides Commands to app 
    */ 
    open var appController: QPSAppController! 


    /** 
    * Returns access to a configuration manager 
    */ 
    open func configurationManager() -> QPSConfigurationManager! 
} 

定義我期望看到的sharedAccessor()單方法上夫特但正如你所看到的那樣,它缺失了。在單獨的swift文件中調用該方法會導致編譯器錯誤,並說sharedAccessor()方法不存在。把所有東西都轉換成Swift是不可行的。建議解決這個問題?

回答

0

經過一番實驗,我發現sharedAccessor()似乎有一些特殊的含義。爲其使用不同的名稱,例如sharedAccessor1()sharedInstance(),爲我工作得很好。一個相關的觀察是,當它不是接口的一部分時嘗試調用sharedAccessor()導致此錯誤:Type QPSSharedAccessor has no member sharedAccessor,這是有道理的。然而,增加sharedAccessor()的Objective-C代碼的結果:

'sharedAccessor()' is unavailable: use object construction 'QPSSharedAccessor()' 

打開錯誤細節揭示更多的光線在此:

'sharedAccessor()' has been explicitly marked unavailable here (__ObjC.QPSSharedAccessor) 

現在,重命名QPSSharedAccessor型別的東西讓sharedAccessor()可以接受的,但是如果新類型名稱是例如QPSMyClass,那麼命名方法myClass()就會成爲問題!

要解決這個奇怪的問題,顯然是與編譯器內部事務,模糊方法命名約定或錯誤有關,您可以簡單地將sharedAccessor()方法重命名爲其他內容。或者,您可以使用C或Objective-C編寫包裝器方法,並通過橋接頭將其提供給Swift。例如:

QPSSharedAccessor * getGlobalQPSSharedAccessor() 
{ 
    return [QPSSharedAccessor sharedAccessor]; 
} 

你也可以添加一個類別QPSSharedAccessor與具有不同的名稱,並委託給sharedAccessor()的方法。

另外,請看看這些引用是有用的:

Can't build in Xcode with error "[method] has been explicitly marked unavailable"

https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html(見單身節)。