较早的时候写了一篇这个文章。不过只是从逻辑、抽象的角度来解释,直接上代码可能更清晰些。
// 这里只是举一个例子,
// 讲的是Controller层遵循这样的协议,
// 而View层握着一个遵循这个协议的类,不知道它实际上是什么,但是知道它会有那个HeyImViewAndTheUserHaveScolledDownHere的方法,
// 来让View层告诉别人用户滑到那了呀,好让Controller层去Model层获取这些个正在被用户阅读着的框框的内容,然后Update这些框框。
protocol ViewLayerTellControllerDelegate : class {
func HeyImViewAndTheUserHaveScolledDownHere()
}
class ViewController : ViewLayerTellControllerDelegate {
func HeyImViewAndTheUserHaveScolledDownHere(){
// the code when the the View is scrolled down there, and what controller need to do.
// maybe the Controller need to fetch the data match the position where the view is now displayed. And update the view, something like that.
}
}
class ViewLayer{
weak var haveToHoldTheDelegateSoThatViewLayerCanKnowWhoItSentTo : ViewLayerTellControllerDelegate?
func whenUserScollToThere(){
haveToHoldTheDelegateSoThatViewLayerCanKnowWhoItSentTo.HeyImViewAndTheUserHaveScolledDownHere()
}
}
class WhenYouIntialEverything{
func youNeedToPutThemTogether(){
ViewLayer. haveToHoldTheDelegateSoThatViewLayerCanKnowWhoItSentTo = ViewController
}
}
// unowned和weak都可以防止循环引用
// 两者的区别在于unowned修饰的对象不可以为可选量也就是说。 用unowned修饰的话要在init马上对这个值进行初始化。
// unowned只允许修饰两种类型:class,class-bound protocol
// weak的话允许它是可选量
// 防止循环引用是让ARC能帮你释放掉那部分的内存。
网友评论