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)に公開するには、
NSAttributedString
ポインタを1つだけ使用し、(2)のように一時的なNSString
を付けないでください。出来ますか? (2番目のinit
は最初のinit
に依存します)シナリオ(1)でコンパイラは何をしますか?私はARCがそれに対してリリース/自動解放を挿入する方法を意味しますか? ARCが有効な場合、(1)にメモリリークがありますか? (ARCで除去
release
のもちろん明示的に呼び出す。)
ありがとうございました!
allocとinitは、目的のCオブジェクトの場合に1回だけ呼び出されますか? – dreamBegin
@dreamBeginちょうど確かめてください。あなたはNSAttributedStringポインタを再利用すべきではないという意味ですか、新しいものを作るべきですか? –
初期化する最初のNSAttributedStringのすべての属性を設定するべきではありませんか? 2番目のNSAttributedStringを作成する必要はありません。 –