如何为 Objective-C 协议提供默认实现? [英] How do I provide a default implementation for an Objective-C protocol?

本文介绍了如何为 Objective-C 协议提供默认实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想指定一个带有可选例程的 Objective-C 协议.当例程不是由符合协议的类实现时,我想在它的位置使用默认实现.协议本身是否有可以定义此默认实现的地方?如果不是,那么减少到处复制和粘贴此默认实现的最佳做法是什么?

I'd like to specify an Objective-C protocol with an optional routine. When the routine is not implemented by a class conforming to the protocol I'd like to use a default implementation in its place. Is there a place in the protocol itself where I can define this default implementation? If not, what is the best practice to reduce copying and pasting this default implementation all over the place?

推荐答案

Objective-C 协议无法提供默认实现.它们纯粹是可以由其他类实现的方法声明的集合.Objective-C 中的标准做法是在运行时测试一个对象,看看它在调用该方法之前是否响应给定的选择器,使用 -[NSObject RespondsToSelector:].如果 e 对象没有响应给定的选择器,则不会调用该方法.

Objective-C protocols have no affordance for default implementations. They are purely collections of method declarations that can be implemented by other classes. The standard practice in Objective-C is to test an object at runtime to see if it responds to the given selector before calling that method on it, using -[NSObject respondsToSelector:]. If e object does not respond to the given selector, the method isn't called.

实现您正在寻找的结果的一种方法是定义一个方法,该方法封装您在调用类中寻找的默认行为,并在对象未通过测试时调用该方法.

One way you could achieve the result you're looking for would be to define a method encapsulating the default behavior you're looking for in the calling class, and call that method if the object doesn't pass the test.

另一种方法是在协议中要求该方法,并在您可能不想提供特定实现的任何类的超类中提供默认实现.

Another approach would be to make the method be required in the protocol, and provide default implementations in the superclasses of any classes wherein you may not want to provide a specific implementation.

可能还有其他选项,但一般来说,Objective-C 中没有特定的标准实践,除非可能只是在对象尚未实现的情况下不调用给定的方法,这是我的第一次段落,上面.

There are probably other options as well, but generally speaking there isn't a particular standard practice in Objective-C, except perhaps to just not call the given method if it hasn't been implement by the object, per my first paragraph, above.

这篇关于如何为 Objective-C 协议提供默认实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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