Objective-c 协议定义在它自己的 .h 文件中? [英] objective-c protocol defined in its own .h file?

查看:49
本文介绍了Objective-c 协议定义在它自己的 .h 文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除非我遗漏了一些东西,否则我将协议定义放在哪个 .h 文件中似乎是任意的.我什至想知道它是否可以在它自己的 .h 文件中......(在 Java 中,它在它自己的文件中)

Unless I'm missing something, it seems arbitrary in which .h file I put the protocol definition. I'm even wondering if it could be in it's own .h file... (in Java, it's in its own file)

推荐答案

我认为协议的位置取决于您如何使用它.很多时候,协议用于为另一个类定义委托或数据源的功能.如果是这种情况,我认为您可以安全地将协议定义放在另一个类的顶部 - 因为它们必须一起使用.

I think the placement of the protocol depends on how you're using it. A lot of the time, a protocol is used to define functionality of a delegate or data source for another class. If that's the case, I think you can safely put the protocol definition at the top of the other class - since they are bound to be used together.

如果您要定义一个协议来代替共享基类,您可能应该将它放在一个单独的文件中.例如,我有几个不同的类来实现操作"协议.我的其他一些函数期望接收一个实现协议的对象,并且不太关心实际的类.在这种情况下,将协议定义放在自己的头文件中是有意义的,这样您就可以将其包含在自己的头文件中.

If you're defining a protocol in place of a shared base class, you should probably put it in a separate file. For instance, I have several different classes that implement the "Operation" protocol. Some of my other functions expect to receive an object implementing the protocol and don't care too much about the actual classes. In that case, it makes sense to put the protocol definition in it's own header file so you can include it on it's own.

Benny 是对的 - 从技术上讲,无论您把它放在哪里,它都会定义(只要它在使用前包含在某处).

Benny is right, though - it will technically be defined no matter where you put it (as long as it's included somewhere prior to it's use).

这篇关于Objective-c 协议定义在它自己的 .h 文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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