方法的条件实现

发布于 2024-08-15 07:40:17 字数 373 浏览 7 评论 0原文

好吧..想想objectA..objectA在其协议中定义了可选属性。代理人可能会或可能不会实施这些,但如果您决定实施它们,您必须提供有效的回报。

现在,如果我将 objectA.delegate 设置为 objectB 但 object 需要在编译时实现所有这些,并在运行时决定它可能支持或不支持哪些。 将它们全部实现为存根的问题意味着 objectA 将简单地使用“respondsToSelector”来查看委托是否正在尝试使用可选属性,如果是,它将假设它们是有效的并使用它们。

由于 objectB(delegate) 必须有条件地决定要实现哪些,我能看到的唯一解决方案是使用“class_addMethod”。

我希望能有一个更优雅、可能更优化的解决方案,但不确定它是什么。

ok.. think of objectA.. objectA has optional properties defined in its protocol. the delegate may or may not implement these, but if you do decide to implement them, you must provide a valid return.

now what if i have objectA.delegate set to objectB but object be needs to implement them all at compile time, and at runtime will decide which ones it may or may not support.
The problem in implementing them all as stubs means that the objectA will simply use 'respondsToSelector' to see if the delegate is trying to use optional properties, and if so it will assume they are valid and use them.

Since objectB(delegate) has to decide conditionally which ones to implement, the only solution i can see is to use 'class_addMethod'.

I was hoping there could be a more elegant and possibly more optimal solution, but not sure as what it may be.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

街道布景 2024-08-22 07:40:17

每当您认为需要使用 class_addMethod() 来实现某些内容时,您几乎总是做错了。

根据您所描述的内容(相当模糊),一个简单的解决方案是创建既可以充当委托又可以根据需要有条件转发方法的东西。

现在,您说如果委托确实实现了一个方法,它必须返回一个有效值。如果是这种情况,class_addMethod() 并没有真正的帮助。大多数实现委托的类将检查一次委托是否实现了该方法,然后假设它永远执行,除非委托发生更改。你可能会经常从事更换代表的工作,但沿着这条路走下去就会变得疯狂。

更好的答案可能是问一个问题; 你想做什么?

Anytime you think you need to use class_addMethod() to implement something, you are almost always doing it wrong.

From what you describe-- which is rather vague-- an easy solution would be to create something that can both act as the delegate and can conditionally forward the methods, as needed.

Now, you say that if the delegate does implement a method it must return a valid value. If that is the case, class_addMethod() isn't really going to help. Most classes that implement delegates will check once if the delegate implements the method and then will assume it does forever unless the delegate changes. You could get into the business of switching delegates often, but down that path lies madness.

A better answer might be to ask a question; what are you trying to do?

紅太極 2024-08-22 07:40:17

是的,将 NSObject 的 + (BOOL)resolveInstanceMethod:(SEL)aSEL 与 class_AddMethod 结合使用,并根据您想要的任何标准连接您想要的实现。不确定这是否是您正在寻找的。希望有帮助。

Yeah, use NSObject's + (BOOL)resolveInstanceMethod:(SEL)aSEL in combination with class_AddMethod and hook up the implementation you want based on whatever criteria you want. Not sure if this is what you are looking for or not. Hope it helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文