7

@propertiesのみを使用するアプリケーションを作成しています。どのクラスファイルでも、1つのivarがまったく宣言されていません。私が理解しているように、@ propertyの導入により、ivarは不要になりました。ベストプラクティスに従ってコーディングしていますか?これは長期的にはことわざのお尻に私を噛むことになりますか?私は「正しい」と「間違っている」についての混合レビューを読んでいます...

4

4 に答える 4

15

インスタンス変数が必要ないということはそれほど多くありません。インスタンス変数の宣言が不要なだけです。プロパティと@synthesizeステートメントを指定すると、コンパイラは適切なアクセサメソッドとともにインスタンス変数の作成を処理します。

プロパティを排他的に使用しても問題はありません。それらはメモリ管理を簡素化します。必要に応じて、プロパティなしでiVarを使用しても問題はありません。プロパティを使用したいが、アクセサを他の世界にアドバタイズしたくない(つまり、カプセル化を維持したくない)場合は、クラス拡張(基本的には実装ファイルの匿名カテゴリ)で非公開プロパティを宣言することを検討してください。

于 2012-01-25T21:39:11.333 に答える
11

私も一般的にivarsを宣言しません。 ただし、方法を介して、またはその逆を意味する場合は、直接アクセスを防ぐためによく使用します。@synthesize foo = foo_;そして、私は常にコンパイラーに接頭辞を付けてivarを自動的に合成させます(これにより、打たれたフレーズ_のように、偶発的な直接アクセスを防ぎます)。

そして、Calebが言ったように、まだivarが浮かんでいるので、本当に必要な場合を除いて、明示的に宣言しないでください(実際、ヘッダーで公開されたivarは、クラスのクライアントにとって有用ではありません)。 、APIが適切に設計されている場合)。

I also find that the hype over "only use direct access in init/dealloc, use setter/getter everywhere else" to be largely overblown and, thus, just use the setter/getter everywhere. The reality is that if you have observers during initialization/deallocation, you are already hosed; the state of the object is, by definition, undefined during construction/destruction and, thus, an observer can't possibly reason correctly about the state.


As Caleb points out, another reason to use direct ivar access in init/dealloc is to avoid subclasses that implement custom setter/getter logic that may barf due to the undefined state of the object during init/dealloc.

While this may be true, I consider it a nasty architectural flaw to implement setters/getters with custom behavior. Doing so is fragile and makes it significantly more difficult to refactor the code over time. As well, such custom behavior will often have dependency on other state within the object and that dependency then leads to order dependencies on state changes that are not at all reflected by the seeming simple @property declaration.

I.e. if your setters and getters are written such that foo.bar = bad; cannot be executed at any time on foo, then your code is busted.

于 2012-01-25T21:40:49.260 に答える
2

iVarsの使用は間違いなく間違いではありませんが、ベストプラクティスでは、代わりに@propertyを使用するようになっています。

于 2012-01-25T21:38:31.920 に答える
0

One place where you may want to use an ivar is when you want to declare a protected property. You declare the property in the .m file for a class, and declare its corresponding ivar in the .h with the @protected directive. This will then let you have a protected access in the subclass. There's no alternative for protected access to members.

于 2013-12-19T18:35:58.383 に答える