最終更新:2013-01-10 (木) 10:07:50 (4117d)  

@synthesize
Top / @synthesize

@synthesize firstName;

Xcode 4.4

  • @synthesizeを省略可能
    • プロパティを宣言すれば、アクセサメソッドとインスタンス変数が自動的に生成される
    • 特に指定しなければ、合成されるインスタンス変数の名前は、プロパティ名の先頭にアンダースコアを置いたものになる

インスタンス変数の省略 (Modern Runtimeのみ)

  • There are differences in the behavior of accessor synthesis that depend on the runtime:
    • For the legacy runtimes, instance variables must already be declared in the @interface block of the current class. If an instance variable of the same name as the property exists, and if its type is compatible with the property’s type, it is used—otherwise, you get a compiler error.
    • For the modern runtimes, instance variables are synthesized as needed. If an instance variable of the same name already exists, it is used.
  • iOS always uses the modern runtime so you never need to declare ivars explicitly.
    • that's either iOS 3.x or greater, or 64-bit Snow Leopard or greater
  • クラスでインスタンス変数を宣言していない場合、コンパイラが合成する

自動生成されるインスタンス変数の名前を変更

  • @synthesize firstName = ivar_firstName;
  • プロパティ名は「firstName」のままであって、「firstName」や「setFirstName?:」というアクセサメソッド、あるいはドット構文でアクセスできるが、その値を保持するインスタンス変数は「ivar_firstName」となる

重要

  • 次のように、インスタンス変数名を指定せずに@synthesizeを記述することもできる。
    @synthesize firstName;
  • この場合、インスタンス変数名はプロパティ名と同じになる
  • この例では、インスタンス変数名もアンダースコアのない「firstName」となる。

関連