ARC または自動ガベージ コレクションを使用しない
-(Fraction*) add: (Fraction*) f
{
Fraction *result = [[Fraction alloc] init];
//To do
return result;
}
//after the function returns. What will the reference count
of object that result was pointing to. See main.m below.
IN main.m
int main(int argc, char* argv[])
{
//To do
Fraction *ans = [[Fraction alloc] init];
ans = [f1 add: f2];
//I guess that the refrence count of the object that ans will be pointing
after this statement will be 1 or 2.
//...
}
//Stephen kochan Objective-C からのこれに関する抜粋
手動のメモリ管理を使用する場合、この方法には問題があります。結果オブジェクトは割り当てられ、計算が実行された後にメソッドから返されます。メソッドはそのオブジェクトを返さなければならないため、それを解放することはできません。その場で破棄されることになります。おそらく、この問題を解決する最善の方法は、オブジェクトを自動解放して値を返すことができるようにすることです。その解放は、自動解放プールが空になるまで延期されます。autorelease メソッドがレシーバーを返し、それを次のような式に埋め込むという事実を利用できます。
Fraction *result = [[[Fraction alloc] init] autorelease];
//or like this:
return [result autorelease];
注 : 抽出によると、refrence カウントは 2 になるようです。そうであれば、その理由を説明してください。