このコードのサンプルコードを見ました:
.hファイル内:
CALayer *_animationLayer;
@property (nonatomic, retain) CALayer *animationLayer;
そして、.mファイルで:
@synthesize animationLayer = _animationLayer;
保持数に関係していると思いますか?
誰かがそれを説明できますか?
このコードのサンプルコードを見ました:
.hファイル内:
CALayer *_animationLayer;
@property (nonatomic, retain) CALayer *animationLayer;
そして、.mファイルで:
@synthesize animationLayer = _animationLayer;
保持数に関係していると思いますか?
誰かがそれを説明できますか?
変数名のエイリアスと考えてください。
の構文に
@synthesize
は、プロパティとそのインスタンス変数ストレージに異なる名前を使用できるようにする拡張機能も含まれています。たとえば、次のステートメントを考えてみましょう。
@synthesize title, directReports, role = jobDescrip;
title
これにより、プロパティ、directReports
、およびrole
のアクセサ メソッドを合成し、 インスタンス変数を使用して プロパティをバックアップするようにコンピュータに指示します。jobDescrip
role
.h ファイル内のコードは、2 つのことを宣言しています。タイプ の変数 と、同じく_animationLayer
タイプCALayer*
のプロパティ が呼び出されanimationLayer
ていCALayer*
ます。.m ファイルのコードは、設定された実際の値を保持する変数をanimationLayer
使用して、プロパティのゲッターとセッターを自動的に生成するように Objective-C コンパイラに指示しています。_animationLayer
たとえば、次のようになります。
_animationLayer = nil; //initialize the variable to nil
self.animationLayer = [[CALayer alloc] init]; //assign a value to the property
NSLog("_animationLayer is: %@", _animationLayer); //it's not set to nil anymore
_animationLayer = nil; //set it to nil again
NSLog("self.animationLayer is: %@", self.animationLayer); //now the property is nil
おっしゃる通り、これはオブジェクトのretainCountと何らかの関係があります(したがって、変数をプロパティの直接のエイリアスと考えるのは正しくありません)。_animationLayer
基本的に、変数を使用して値を直接設定しても、新しい値が保持されたり、古い値が解放されたりすることはありません。プロパティアクセサーを使用して値を設定します。例えば:
_animationLayer = [[CALayer alloc] init]; //retain count is 1
self.animationLayer = nil; //retain count is 0
self.animationLayer = [[CALayer alloc] init]; //oops, retain count is 2
self.animationLayer = nil; //retain count is 1, the object leaked
_animationLayer = [[CALayer alloc] init]; //retain count is 1
[_animationLayer release]; //retain count is 0
self.animationLayer = nil; //oops, just released it again