在 Cocoa 中,将私有 API 放在 .m 文件中,将公共 API 放在 .h 文件中是一个好习惯吗?

发布于 2024-08-27 17:11:17 字数 180 浏览 5 评论 0原文

我当前项目中的许多类都有几个只能从类本身内部调用的属性和方法。此外,根据班级的当前状态,它们可能会扰乱班级的工作。
目前,所有这些接口都在 .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 技术交流群。

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

发布评论

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

评论(2

暮凉 2024-09-03 17:11:17

从 Objective-C 2.0 开始,最佳实践是将私有方法放在“类扩展”中。如果您尚未实现其中一种方法,这允许编译器向您发出警告。类扩展还允许您修改 @properties 的读/写语义,以便公共 API 可以为属性指定只读属性,而在内部该属性可以用作读写属性代码>.

在 .h 中:

@interface MyClass : NSObject
{}

@property (readonly) id myProp;

- (void)aPublicMethod;
@end

在 .m 中:

@interface MyClass ()
@property (readwrite) id myProp; //upgrade myProp to readwrite within the class.

- (id)aPrivateMethod;
@end

@implementation MyClass
@synthesize myProp;

- (void)aPublicMethod { ... }

- (id)aPrivateMethod;

@end

如果您忘记在主 @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 as readwrite.

In .h:

@interface MyClass : NSObject
{}

@property (readonly) id myProp;

- (void)aPublicMethod;
@end

In .m:

@interface MyClass ()
@property (readwrite) id myProp; //upgrade myProp to readwrite within the class.

- (id)aPrivateMethod;
@end

@implementation MyClass
@synthesize myProp;

- (void)aPublicMethod { ... }

- (id)aPrivateMethod;

@end

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.

蓝海似她心 2024-09-03 17:11:17

是的,将它们放在 .m 文件顶部的类别中。

Yes, put them in a category at the top of your .m files.

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