订阅一个属性
我有一个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函数中的打印消息永远不会显示。
您可以使用委托模式,并让该类想要使用您的事件来实现协议中的功能。
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()
{
}
}
我试着用这种方式来实现它,但无法让它编译。我已经提到了这个:https://www.andrewcbancroft.com/2015/04/08/how-delegation-works-a-swift-developer-guide/和https://*.com/questions/29536080/swift-set-delegate-for-singleton - 我已经添加了我目前的非工作但编译解决方案的问题。 –
说实话,我甚至不确定这是做到这一点的最佳方式 - 我基本上只是试图使用服务类来获取标题并将其发送到ui视图类,以便它可以适当地重绘。 –
您可以使用委托模式,也可以让单例在标题更改时发布“通知”。您的视图然后可以订阅此通知。 – Paulw11