慕标5832272
代表们总是把我搞糊涂直到我意识到委托只是一个为另一个类做一些工作的类。..这就像有别人为你做所有你不想做的肮脏工作。我写了一个小故事来说明这一点。如果你愿意的话,可以在游乐场里读一读。很久以前.。// MARK: Background to the story// A protocol is like a list of rules that need to be followed.protocol OlderSiblingDelegate: class {
// The following command (ie, method) must be obeyed by any
// underling (ie, delegate) of the older sibling. func getYourNiceOlderSiblingAGlassOfWater()}
// MARK: Characters in the storyclass BossyBigBrother {
// I can make whichever little sibling is around at
// the time be my delegate (ie, slave) weak var delegate: OlderSiblingDelegate?
func tellSomebodyToGetMeSomeWater() {
// The delegate is optional because even though
// I'm thirsty, there might not be anyone nearby
// that I can boss around. delegate?.getYourNiceOlderSiblingAGlassOfWater()
}}// Poor little sisters have to follow (or at least acknowledge)
// their older sibling's rules (ie, protocol)class PoorLittleSister: OlderSiblingDelegate {
func getYourNiceOlderSiblingAGlassOfWater() {
// Little sis follows the letter of the law (ie, protocol), // but no one said exactly how she had to respond.
print("Go get it yourself!")
}}// MARK: The Story// Big bro is laying on the couch watching basketball on TV.let bigBro = BossyBigBrother()
// He has a little sister named Sally.let sally = PoorLittleSister()// Sally walks into the room. How convenient! Now big bro
// has someone there to boss around.bigBro.delegate = sally// So he tells her to get him some water.bigBro.tellSomebodyToGetMeSomeWater()
// Unfortunately no one lived happily ever after...// The end.在评审中,编写和使用委托模式有三个关键部分。这个协议,它定义了工人需要做的事情。这个老板班它有一个委托变量,它用来告诉Worker类要做什么。这个工人阶级它采用了协议,并执行了所需的操作。现实生活与以上我们的波西老大哥故事相比,代表们经常被用于下列实际应用:通讯一个类需要向另一个类发送一些信息。代码示例1:将数据从一个视图控制器发送到另一个视图控制器代码示例2:从自定义键盘向文本字段发送文本输入定制化一个类希望允许另一个类自定义它。最重要的是,这些类不需要事先了解彼此的任何信息,只需要委托类符合所需的协议。我强烈建议阅读以下两篇文章。他们帮助我更好地理解了代表们文献资料做。什么是授权?-迅捷的开发者指南授权是如何运作的-快速开发人员指南再来一个音符引用它们不拥有的其他类的委托应该使用weak关键字以避免强引用周期。看见这个答案更多细节。