2017-06-13 162 views
1

我有一個singleton服務類,它維護從指南針獲取標題的值。我有一個UIView,它基於此繪製一些自定義圖形。我正在嘗試在JavaScript中執行類似Observable的操作,其中的代碼在值發生更改時執行。訂閱一個屬性

final class LocationService: NSObject { 

static let shared = LocationService() 

public var heading:Int 

public func getHeading() -> Int { 

    return self.heading 

} 

然後在我UIView子類:

var ls:LocationService = LocationService.shared 

var heading: Int = ls.getHeading() { 
    didSet { 
     setNeedsDisplay() 
    } 
} 

我想也只是直接訪問通過ls.heading財產,但這沒有得到任何接受。它告訴我我不能在屬性初始化器中使用實例成員。什麼是適當的快速方法呢?

編輯:

我一直與基督教的回答下面還有一些其他的文件,現在得在這兒,這一切編譯好聽,但實際上並沒有正常工作。這是我的委託人和協議:

final class LocationService: NSObject { 

    static let shared = LocationService() 

    weak var delegate: CompassView? 

    var heading:Int 

    func headingUpdate(request:HeadingRequest, updateHeading:CLHeading) { 

     print ("New heading found: \(updateHeading)") 

     self.heading = Int(updateHeading.magneticHeading) 
     self.delegate?.setHeading(newHeading: Int(updateHeading.magneticHeading)) 

    } 

    public func getHeading() -> Int { 

     return self.heading 

    } 

} 

protocol LSDelegate: class { 

    func setHeading(newHeading:Int) 

} 

然後在委託:

class CompassView: UIView, LSDelegate { 

    func setHeading(newHeading:Int) { 
     self.heading = newHeading 

     print("heading updated in compass view to \(self.heading)") 

     setNeedsDisplay() 
    } 

} 

所以我得到的標題已經在headingUpdate功能進行了更新打印消息。委託CompassView中的setHeading函數中的打印消息永遠不會顯示。

+2

您可以使用委託模式,也可以讓單例在標題更改時發佈「通知」。您的視圖然後可以訂閱此通知。 – Paulw11

回答

2

您可以使用委託模式,並讓該類想要使用您的事件來實現協議中的功能。

protocol MyDelegate { 
    func setNeedsDisplay() 
} 

class LocationService: NSObject { 
    var myDelegate : MyDelegate? 

    var heading: Int = ls.getHeading() { 
    didSet { 
     myDelegate?.setNeedsDisplay() 
    } 
    } 

    ... 
    func assignDelegate() { 
    self.myDelegate = MyConsumer() 
    } 
} 

class MyConsumer : MyDelegate { 
    func setNeedsDisplay() 
    { 
    } 
} 
+0

我試着用這種方式來實現它,但無法讓它編譯。我已經提到了這個:https://www.andrewcbancroft.com/2015/04/08/how-delegation-works-a-swift-developer-guide/和https://stackoverflow.com/questions/29536080/swift-set-delegate-for-singleton - 我已經添加了我目前的非工作但編譯解決方案的問題。 –

+0

說實話,我甚至不確定這是做到這一點的最佳方式 - 我基本上只是試圖使用服務類來獲取標題並將其發送到ui視圖類,以便它可以適當地重繪。 –