2016-06-07 74 views
0

你好,大家好,我有以下代碼不能使用一個單獨的類返回其屬性

class DeviceListViewController { 
    private var currentPeripheral:BLEPeripheral? 

    public class var sharedInstance: DeviceListViewController { 
     struct Singleton { 
      static let instance = DeviceListViewController() 
     } 
     return Singleton.instance 
    } 

    func getCurrentPeripheral() -> BLEPeripheral? { 
     return currentPeripheral 
    } 

} 

但是,當我使用這個另一類像下面

DeviceListViewController.getCurrentPeripheral() 

它給了我一個錯誤說服力我以下 在「DeviceListViewController」類型上使用實例成員「getCurrentPeripheral」;你的意思是使用「DeviceListViewController」類型的值嗎?

我不知道我在做什麼錯在這裏。有關如何解決這個問題的任何建議?

p.s. Xcode中的自動完成功能與它通過視圖控制器作爲參數一起莫名其妙

DeviceListViewController.getCurrentPeripheral(DeviceListViewController) 

但它導致了同樣的錯誤

回答

2

你需要調用共享實例的方法,而不是通過類

DeviceListViewController.sharedInstance.getCurrentPeripheral() 
+0

感謝您的幫助!但是,我是否需要始終使用共享實例?就像我在Devicelistviewcontroller中連接設備時一樣,我應該使用DeviceListViewController.SharedInstance.connectPeripheral而不是connectPeripheral? – Reshad

+0

你的意思是什麼?*在Devicelistviewcontroller *中連接設備?如果控制器是UI視圖層次結構的一部分,則根本不需要共享實例。 – vadian

+0

那麼可以說,我有另一個內部的DeviceListViewController方法來做一些事情。它是通過共享實例還是像通常的方式調用自己的屬性?因爲如果我使用共享實例來獲取當前外設,即使我知道連接了某些東西,它也會返回零。 – Reshad

0

要避免使用MyClass.sharedInstance.method(),你可以用這個方法:

class DeviceListViewController { 
    private var currentPeripheral:BLEPeripheral? 

    public class var sharedInstance: DeviceListViewController { 
     struct Singleton { 
      static let instance = DeviceListViewController() 
     } 
     return Singleton.instance 
    } 

    class func getCurrentPeripheral() -> BLEPeripheral? { 
     return DeviceListViewController.sharedInstance.currentPeripheral 
    } 

} 

現在您可以使用MyClass.method()