【发布时间】:2026-01-30 07:50:01
【问题描述】:
每当我想向父类通知某些内容时,我都会使用委托而不是直接调用父类的函数。我是这样实现的……
例如:
CustomClass *custom = [[CustomClass alloc] init];
// assign delegate
custom.delegate = self; // Here we are giving parent instance like normal method call.
[custom helloDelegate];
在自定义类中,我已经像下面这样暗示了父母......
-(void)helloDelegate
{
// send message the message to the delegate
[_delegate sayHello:self];
}
所以我的疑问,它与直接调用有何不同?使用 self 设置委托变量在某种程度上等于将父实例赋予子实例并让子实例在需要时调用该函数,协议在这里有什么帮助或者我们为什么需要协议?有什么优势?
感谢
【问题讨论】:
-
促进松耦合
-
如果你从不改变你的代表,那是一样的,如果你的代表可以不止一件事,那就不同了。
-
“通知父类”是什么意思?如果您在派生类中,那么派生类本身就是父类的一个版本。虽然如果你想向父类通知一些东西,请使用 [super methodName:]。
-
@zneak 你能提供更多关于它的信息吗?
-
@CodenameLambda1 它不是派生的.. 自定义类是从父类加载的...
标签: ios objective-c methods delegates protocols