2016-12-15 6 views
0

Objective-Cを書くとき、ARCの助けを借りても、どのようにメモリを管理するかを知ることが重要です。ここで自分自身を初期化するオブジェクトを解放する方法

は、コードスニペット(非ARC)である:

(1)ここで

NSAttributedString *tmpAttrbutedString = [[NSAttributedString alloc] initWithString:@"foo" attributes:@{NSFontAttributeName:[NSFont fontWithName:@"Heiti SC" size:13.0f]}]; 
// how should I release tmpAttributedString here? 
tmpAttributedString = [[NSAttributedString alloc] initWithString:tmpAttributedString.string attributes:@{NSForegroundColorAttributeName:[NSColor redColor]}]; 
[tmpAttributedString release]; 

私は現在、メモリリークを避けるために何をすべきかです:

(2)

NSAttributedString *tmpAttrbutedString = [[NSAttributedString alloc] initWithString:@"foo" attributes:@{NSFontAttributeName:[NSFont fontWithName:@"Heiti SC" size:13.0f]}]; 
NSString *tmpString = tmpAttrbutedString.string; 
[tmpAttrbutedString release]; 

tmpAttributedString = [[NSAttributedString alloc] initWithString:tmpString attributes:@{NSForegroundColorAttributeName:[NSColor redColor]}]; 
[tmpAttributedString release]; 

私の質問は:

  1. を(1)に公開するには、NSAttributedStringポインタを1つだけ使用し、(2)のように一時的なNSStringを付けないでください。出来ますか? (2番目のinitは最初のinitに依存します)

  2. シナリオ(1)でコンパイラは何をしますか?私はARCがそれに対してリリース/自動解放を挿入する方法を意味しますか? ARCが有効な場合、(1)にメモリリークがありますか? (ARCで除去releaseのもちろん明示的に呼び出す。)

ありがとうございました!

+0

allocとinitは、目的のCオブジェクトの場合に1回だけ呼び出されますか? – dreamBegin

+0

@dreamBeginちょうど確かめてください。あなたはNSAttributedStringポインタを再利用すべきではないという意味ですか、新しいものを作るべきですか? –

+0

初期化する最初のNSAttributedStringのすべての属性を設定するべきではありませんか? 2番目のNSAttributedStringを作成する必要はありません。 –

答えて

0

ARCのルールは比較的簡単です。 allocnew、またはcopyを呼び出した場合、ARCは範囲外になったときにこのオブジェクトにreleaseを呼び出す必要があることを認識しています。その他のオブジェクトはすべてautoreleasedとします。 「範囲外に出る」とは、変数の返却または再割当てを意味します。変数の再割り当てがある場合は、暗黙のうちに別のものに割り当てられる前にreleaseコールを入れます。変数を返すと、ARCはその変数にautoreleaseの呼び出しを行い、メソッドのスコープ外で終了することができます。返されないがまだ存在する他の既存の変数(オートレリースされていないもの)は暗黙的にreleaseが送られます。

Apple's official transition guideを参照してください。

関連する問題