简体   繁体   English

应该在标头或实现文件中声明ivars和属性吗?

[英]Should ivars and properties be declared in the header or the implementation file?

I want to know which of these is considered "best practice" for iOS development: 我想知道以下哪一项被认为是iOS开发的“最佳实践”:

  1. Declare all ivars and properties inside the .h file, so that anyone can understand the structure of the class. 在.h文件中声明所有ivars和属性,以便任何人都可以理解该类的结构。

  2. Declare all ivars within the @implementation block, in the .m file and declare necessary properties in .h file. 在.m文件中的@implementation块中声明所有ivars,并在.h文件中声明必要的属性。 (Also, if necessary declare some properties in .m file for internal use). (此外,如有必要,请在.m文件中声明一些属性以供内部使用)。 The idea here being that others don't have to bother about my structure and implementation, they can just use my code. 这里的想法是,其他人不必理会我的结构和实现,他们只需使用我的代码即可。

It really is up to personal preference and differs on each project. 这实际上取决于个人喜好,并且在每个项目上都不同。 Here are a couple examples: 这是几个例子:

When creating a framework, you will want to include only the properties and methods that you want others to see, as the .h file will be the only file they can really look into. 创建框架时,您将只希望包含其他人可以看到的属性和方法,因为.h文件将是他们真正可以查看的唯一文件。

When working with a team on a large project, you may want to put more into the .h file so that when you track down a bug in a part of the code you didn't write, you know where to look to find the property. 与团队一起处理大型项目时,您可能希望将更多内容放入.h文件中,以便在未编写的部分代码中查找错误时,您知道可以在哪里找到该属性。

I think most example online treat the header file as the "public" properties, and the .m as the "private" (even though they are not really private). 我认为大多数在线示例都将头文件视为“公共”属性,将.m视为“私有”属性(即使它们不是真正的私有属性)。

Anyway, as far as I have seen there is not a "best practice." 无论如何,据我所知,还没有“最佳实践”。 Just make sure that you pick a method and stick to it throughout the project so that you have consistency. 只需确保选择一种方法并在整个项目中坚持使用它,即可保持一致性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM