iOS:委托模式(Swift)(markdown重制)

较早的时候写了一篇这个文章。不过只是从逻辑、抽象的角度来解释,直接上代码可能更清晰些。

// 这里只是举一个例子,
// 讲的是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能帮你释放掉那部分的内存。

unowned和weak区别1

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容