斯威夫特的代表链

时间:2016-02-04 15:19:24

标签: ios swift

TDLR; 我有三个类,当Class A对象更新时,它会调用其委托(Class B)来调用其委托( Class C)没有做任何其他事情。 Class C将以不同的方式使用Class B,具体取决于Class A中的值。 Class B需要了解其Class A触摸事件。这可以接受吗?

classA { var information: String }
classB { var thing: ClassA thing.delegate = self }
classC { var things: [ClassB] for thing in things { thing.delegate = self } } 

我真实的例子

我有三个课程:A mapViewControllermapMarkerplace(模型)。地图包含多个mapMarker,每个mapMarker都有一个属性place,其中包含标记应该是什么样的信息(如地点类型," bar" ,"餐厅"等)。该地点可能通过静音推送通知接收新信息,因此正在更新。当地点更新时,我需要通知mapViewController标记需要重新绘制(我使用MapBox并且他们的注释不支持以任何方式重绘,但删除并添加标记再次,因为imageForAnnotation方法是委托方法。)

我的第一个想法是制定两个协议placeDelegatemapMarkerDelegate

地点:

protocol PlaceDelegate: class
{
  func placeUpdated()
}

class Place {
    weak var delegate: PlaceDelegate?

    var propertyThatCanBeUpdate: String {
        didSet { 
        //Checking if the newValue == oldValue 
        delegate.placeUpdated()
        }
}

MapMarker

protocol MapMarkerDelegate: class
{
    markerShouldReDraw(mapMarker: MapMarker)
}

class MapMarker: PlaceDelegate {
    var place: Place!
    weak var delegate: MapMarkerDelegate?
    init(place: Place) {
        self.place = place
        place.delegate = place
    }

    func placeUpdate()
    {
        delegate.markerShouldReDraw(self)
    }

} 

的MapViewController

class MapViewController {
//I could easily set the marker.delegate = self when adding the markers

func markerShouldReDraw(mapMarker: MapMarker)
    functionForRedrawingMarker()
}

这感觉有点难看,有点奇怪的是MapMarker正在传递"我的位置已经更新了#34;信息转发。就性能而言,这是否可以接受?我应该使用某种NSNotification吗?我应该MapViewController代理place,并搜索我的mapMarker数组以查找持有正确place的代理人吗?

0 个答案:

没有答案