0

このコードのサンプルコードを見ました:

.hファイル内:

  CALayer *_animationLayer;
  @property (nonatomic, retain) CALayer *animationLayer;

そして、.mファイルで:

  @synthesize animationLayer = _animationLayer;

保持数に関係していると思いますか?

誰かがそれを説明できますか?

4

2 に答える 2

2

変数名のエイリアスと考えてください。

Cocoa Fundamentals Guideから:

の構文に@synthesizeは、プロパティとそのインスタンス変数ストレージに異なる名前を使用できるようにする拡張機能も含まれています。たとえば、次のステートメントを考えてみましょう。

@synthesize title, directReports, role = jobDescrip;

titleこれにより、プロパティ、directReports、および roleのアクセサ メソッドを合成し、 インスタンス変数を使用して プロパティをバックアップするようにコンピュータに指示します。jobDescriprole

于 2011-03-20T07:44:53.193 に答える
1

.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
于 2011-03-20T07:59:43.347 に答える