Wenn Sie Objective-C schreiben, ist es wichtig, zu wissen, wie der Speicher verwaltet wird, selbst mit Hilfe von ARC.So geben Sie ein Objekt frei, das es initialisiert
ist hier ein Code-Schnipsel (non-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];
Hier ist, was ich tun, um momentan Speicherlecks zu vermeiden:
(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];
Meine Fragen sind:
Wie soll ich
tmpAttributedString
in (1), mit nur einemNSAttributedString
Zeiger und ohne temporäreNSString
wie in (2) freigeben? Ist es möglich? (Die zweiteinit
hängt von der ersteninit
ab.)Was würde der Compiler in Szenario (1) tun? Ich meine, wie ARC Release/Autorelease dafür einfügen würde? Gibt es Speicherverlust in (1), wenn ARC aktiviert ist? (Natürlich expliziter Aufruf von
release
mit ARC entfernt.)
Thank you!
alloc und init werden nur einmal bei einem objektiven C-Objekt aufgerufen? – dreamBegin
@dreamBegin Nur um sicher zu gehen. Meinst du, ich sollte NSAtributedString Zeiger nicht wiederverwenden, und sollte einen neuen machen? –
Sollten Sie nicht alle Attribute auf dem ersten initialisierten NSAtributedString setzen? Der zweite NSAttributedString muss nicht erstellt werden. –