【发布时间】:2016-08-05 10:12:44
【问题描述】:
经过大量研究后,我仍然对如何使用和实现委托感到有些困惑。我已经尝试编写自己的简化示例来帮助我理解 - 但是它不起作用 - 这意味着我一定有点迷茫。
//the underlying protocol
protocol myRules {
func sayName(name: String);
}
//the delegate that explains the protocols job
class myRulesDelegate: myRules {
func sayName(name: String){
print(name);
}
}
//the delegator that wants to use the delegate
class Person{
//the delegator telling which delegate to use
weak var delegate: myRulesDelegate!;
var myName: String!;
init(name: String){
self.myName = name;
}
func useDels(){
//using the delegate (this causes error)
delegate?.sayName(myName);
}
}
var obj = Person(name: "Tom");
obj.useDels();
我已经阅读并观看了很多教程,但仍在苦苦挣扎。我不再得到错误(干杯家伙)。但仍然没有从 sayName 得到任何输出。
这表明我一定误解了委托模式的工作原理。 我真的很感谢代码的更正版本,并简单解释了它的工作原理以及它为什么有用。
我希望这对其他人也有帮助。干杯。
【问题讨论】:
-
您在使用之前忘记分配代理。喜欢
obj.delegate = myRulesDelegate()。而且由于它是一个隐式展开的可选项,它会崩溃。请参阅 Paulw11 的回答。
标签: ios swift design-patterns delegates