我知道这里有很多类似的问题,但我仍然需要澄清一下这个概念。
首先让我先说我确实了解什么是协议(protocol)以及如何使用它们,我在理解方面遇到的问题是委派。我理解委托(delegate)是程序中的一个对象委托(delegate)另一个对象,听起来很简单但很难看清全貌。
1- 委托(delegate)是否只是让编译器知道在哪里寻找将要操作对象(UITableView 等)的代码的一种方式?
2- 委托(delegate)和协议(protocol)是否协同工作?
3- 委托(delegate)可以没有协议(protocol)吗?如果是,你能给我举个例子吗?
4- 当我们声明一个协议(protocol)并且一个类符合它时,我们可以说这个符合协议(protocol)的类正在委托(delegate)协议(protocol)的行为吗?
以上有多少是正确的?
非常感谢
最佳答案
1- Is delegation just a way to let the compiler know where to look for the code that will be manipulating the object (UITableView etc.)?
不,委托(delegate)是一种设计模式。这只是一个概念。
2- Do delegation and protocols work together?
是的,它们可以很好地协同工作,为您的委托(delegate)使用协议(protocol)可能是最佳实践。
3- Can delegation exist without protocols? If yes, can you show me an example.
是的,你可以。委托(delegate)概念只是删除对象的智能并将其放入委托(delegate)中。例如,UITableView
不知道它有多少行,或者当一个单元格被点击时要做什么,所以它会询问它的委托(delegate)。
但是委托(delegate)仍然是另一个对象。
如果它实现了一个特定的协议(protocol)会更好,但你可以不实现它。
例如:
我有一个 MyView,它是 MyCustomViewController
的 subview 。
MyCustomViewController.h
- (void)myViewIsTouched;
MyView.h
@property (nonatomic, weak) MyCustomViewController *delegate
MyView.m
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.delegate myViewIsTouched];
}
这个例子中没有协议(protocol),但它仍然是一个委托(delegate)。
(更好的方法仍然是使用协议(protocol)而不是在 .h
中声明方法)
4- When we declare a protocol and a class conforms to it, can we say that this class conforming to the protocol is delegating on behave of the protocol?
我不确定在说什么。但是协议(protocol)和委托(delegate)不是一回事。实现协议(protocol)的对象并不意味着它是委托(delegate)。
关于ios - 理解授权和协议(protocol)之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28500018/