且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该在接口中声明变量还是在objective-c arc中使用属性?

更新时间:2023-11-10 18:06:40

最现代的方式 1


  • 尽可能声明属性

  • 不要单独声明iVars 2

  • 不要@synthesize 3

  • 在你.h文件中找到尽可能少的属性 4

  • 在.m文件的类扩展中找到尽可能多的属性 5

  • whenever possible, declare properties
  • don't declare iVars separately 2
  • don't @synthesize 3
  • locate as few properties as possible in you .h file 4
  • locate as many properties as possible in a class extension in your .m file 5

1 自Xcode 4.5.2起。其中大部分适用于4.4,其中一些不会在4.2(Snow Leopard下的最新版本)上编译。这是预处理器的东西,所以它至少与iOS5完全兼容(我没有在iOS4上测试,但也应该没问题)。

1 As of Xcode 4.5.2. Most of this applies back to 4.4, some of it won't compile on 4.2 (the last version available under Snow Leopard). This is preprocessor stuff, so it is all compatible back at least to iOS5 (I haven't tested on iOS4 but that should also be OK).

2 宣布iVar 以及属性是没有意义的。我确信有一些不起眼的情况,你想要声明iVars 而不是的属性,但我想不出任何。

2 There is no point in declaring an iVar as well as a property. I am sure there are a few obscure cases where you would want to declare iVars instead of properties but I can't think of any.

3 Xcode将创建一个与该属性同名的iVar,前面是_underscore。如果您(很少)需要其他类型的行为,您可以手动 @synthesize property = someOtherName 。 @vikingosegundo将我们链接到关于动态ivars的这篇文章,这是一个用例 @synthesize 。 @RobNapier评论你需要 @synthesize iVar = _iVar (奇怪)如果你正在创建自己的getterly(readonly)和setters(读取) / write)对于一个属性,因为在这种情况下预处理器不会为你生成iVar。

3 Xcode will create an iVar with the same name as the property, preceded by an _underscore. If you (rarely) need some other kind of behaviour, you can manually @synthesize property = someOtherName. @vikingosegundo links us to this article on dynamic ivars, which is a use case for @synthesize. @RobNapier comments that you do need to @synthesize iVar = _iVar (bizarrely) if you are creating your own getters (readonly) and setters (read/write) for a property, as in this case the preprocessor will not generate the iVar for you.

4 你的界面的一般规则:尽可能保持空白。如果它们是供私人使用的话,您现在根本不需要声明方法。如果你可以在没有接口声明的情况下使代码工作,那就是你要走的路。

4 The general rule with your interface: keep it as empty as possible. You don't actually need to declare your methods now at all, if they are for private use. If you can get the code to work without an interface declaration, that's the way to go.

5 这是.m文件中的@interface块,位于@implementation上方:

5 This is an @interface block in your .m file, placed above your @implementation:

#TestClass.m

@interface TestClass()

//private property declarations here

@end

@implementation TestClass
...