0

アーロンヒレガスによるMacOSX用Cocoaプログラミングの第8章からこのプログラムを実行すると、エラーが発生します。プログラムは、テーブルビューをアレイコントローラーにバインドします。配列コントローラーのsetEmployeesメソッドで、

-(void)setEmployees:(NSMutableArray *)a
{
    if(a==employees)
        return;
    [a retain];//must add
    [employees release]; //must add
    employees=a;
}

この本には、2つのretainステートメントとreleaseステートメントが含まれておらず、新しい従業員を追加しようとするとプログラムがクラッシュします。グーグルした後、プログラムのクラッシュを防ぐために、これら2つの追加する必要のあるステートメントを見つけました。ここでのメモリ管理がわかりません。に割り当てaていemployeesます。割り当てを解除しないのに、なぜ保持する必要がaあるのですか?employees最後の代入ステートメントで使用する前にリリースできるのはなぜですか?

4

1 に答える 1

2

これは手動参照カウント (MRC) を使用するセッターの標準パターンです。ステップごとに、これはそれがすることです:

-(void)setEmployees:(NSMutableArray *)a 
{ 
    if(a==employees) 
        return;          // The incoming value is the same as the current value, no need to do anything. 
    [a retain];          // Retain the incoming value since we are taking ownership of it
    [employees release]; // Release the current value since we no longer want ownership of it
    employees=a;         // Set the pointer to the incoming value
} 

自動参照カウント (ARC) では、アクセサーは次のように簡略化できます。

 -(void)setEmployees:(NSMutableArray *)a 
    { 
        if(a==employees) 
            return;          // The incoming value is the same as the current value, no need to do anything. 
        employees=a;         // Set the pointer to the incoming value
    } 

保持/解放はあなたのために行われます。どのような種類のクラッシュが発生しているのかは述べていませんが、MRC プロジェクトで ARC サンプル コードを使用しているようです。

于 2012-07-24T09:33:26.567 に答える