强制变量声明的协议 - Objective C
是否可以在@protocol中声明变量?只是为了强制程序员在实现类(实现此协议的类)标头和实现中添加这些变量?
谢谢
Is it possible to declare variable in @protocol? Just to force programmers to add those variable in implementing class's(classes which implements this protocol) header and implementation?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简短的回答:不,不可能这样做。您最多可以强制方法和属性的可用性。
Short answer: No, it isn't possible to do that. You can enforce the availability of methods and properties at most.
您不能在 @protocol 中声明 ivars,但您可以强制一致的类实现访问器和修改器,这听起来像您所得到的。例如:
You can't declare ivars in
@protocol
s but you can force the conforming class to implement an accessor and a mutator, which sounds like what you're getting at. For example:您可以将对象设为具体的子类。这是确保它们包含您需要的内部结构的唯一方法。当然,如果您对类如何在内部存储数据感兴趣……这违反了一些 oop 范例。
You could make the objects a concrete subclass. That would be the only way to ensure that they contained the internals that you needed. Of course if you are interested in how the classes are storing their data internally... That is violating some oop paradigms.