从父母发送消息给孩子 [英] Sending message to child from parent

查看:83
本文介绍了从父母发送消息给孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有从Parent类继承的类Child。我想要的是向子节点发送消息,该节点具有该消息的实现。所以这就像从父级调用纯虚函数。如果我现在从Parent发送消息,我将收到警告,父母可能不会回复此消息。确实如此,因为只有Child才能实现它。

I have class Child inherited from class Parent. What I want is to send message to child, which has implementation of that message. So it's like calling pure virtual function from parent. If I send message now from Parent I'll get warning that Parent may not respond to this message. It is true, because only Child has implementation of it.

基本上,Parent会检测一些操作,例如点击取消按钮,但是每个孩子都有自己的取消消息实现,所以我想从Parent <$ c $打电话c> onCancel 让他们完成工作。

Basically Parent will detect some action like tap on cancel button, but each child has its own implementation of that cancel message, so I want to call from Parent onCancel to let them do their job.

不能相信使用继承我仍然需要使用委托...

Can't believe that using inheritance I still have to use delegates...

推荐答案

是否在运行时检查方法是否存在。因此,即使编译器警告您,代码仍然可以成功。但总是检查 self 是否真的首先定义了该方法。

Whether the method is present is checked at runtime. Therefore, even if the compiler warns you, the code could still succeed. But always check if self really defines that method first.

if ([self respondsToSelector:@selector(onCancel)]) {
  [self onCancel];
}

如果您想消除警告,请使用 - performSelector:

If you want to eliminate the warning, use -performSelector:.

if ([self respondsToSelector:@selector(onCancel)]) {
  [self performSelector:@selector(onCancel)];
}

这篇关于从父母发送消息给孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆