在 Cocoa 中,将私有 API 放在 .m 文件中,将公共 API 放在 .h 文件中是一个好习惯吗?
我当前项目中的许多类都有几个只能从类本身内部调用的属性和方法。此外,根据班级的当前状态,它们可能会扰乱班级的工作。
目前,所有这些接口都在 .h 文件的主接口声明中定义。将“私有”方法和属性放在 .m 文件的顶部是否被认为是好的做法?
这不会影响任何事情,因为我很可能是唯一查看此源代码的人,但当然了解未来的项目会很有趣。
Many of my classes in my current project have several properties and methods that are only ever called from within the class itself. Also, they might mess with the working of the class depending on the current state of the class.
Currently, all these interfaces are defined in the main interface declaration in the .h files. Is it considered good practice to put the “private” methods and properties at the top of the .m files?
This won't ever affect anything since I am very likely the only person ever to look at this source code, but of course it would be interesting to know for future projects.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从 Objective-C 2.0 开始,最佳实践是将私有方法放在“类扩展”中。如果您尚未实现其中一种方法,这允许编译器向您发出警告。类扩展还允许您修改 @properties 的读/写语义,以便公共 API 可以为属性指定只读属性,而在内部该属性可以用作读写属性代码>.
在 .h 中:
在 .m 中:
如果您忘记在主
@implementation
块中实现-aPrivateMethod
,编译器将发出警告。这比使用像@interface MyClass (PrivateMethods)
这样的类别的旧方法要好,在这种情况下,编译器无法警告您该方法尚未实现。Starting with Objective-C 2.0, the best practice is to put private methods in a "class extension". This allows the compiler to warn you if you haven't implemented one of the methods. Class extensions also let you modify the read/write semantics of @properties so that the public API can, for example, specificy
readonly
for a property while internally the property can be used asreadwrite
.In .h:
In .m:
If you forget to implement
-aPrivateMethod
within the main@implementation
block, the compiler will give a warning. This is better than the old way of using a category like@interface MyClass (PrivateMethods)
in which case, the compiler couldn't warn you that the method wasn't implemented.是的,将它们放在 .m 文件顶部的类别中。
Yes, put them in a category at the top of your .m files.