仍在學習iOS開發具有的ObjectiveC和iOS,並試圖瞭解真的內存管理!欣賞下面的代碼片段任何意見,如: 1)分析說,有潛在的內存泄漏,但解決不了呢? 2)我應該保持alloc和初始化NSString在for循環中,並且當附加到?iOS的內存管理和NSString的初始化
感謝
- (NSString *) lookUpCharNameForID: (NSString *) inCharID
{
debugPrint ("TRACE", [[@"Lookup Char Name for = " stringByAppendingString: inCharID] UTF8String]);
NSString *tempName = [[NSString alloc] initWithFormat: @""];
if (![inCharID isEqualToString: @""])
{
// Potentially lookup multiple values
//
NSString *newName = [[NSString alloc] initWithFormat: @""];
NSArray *idList = [inCharID componentsSeparatedByString: @","];
for (NSString *nextID in idList)
{
NSLog(@"Lookup %i : %@", [idList count], nextID);
newName = [[NSString alloc] initWithFormat: @"C%@", nextID];
// Append strings
if ([tempName isEqualToString: @""])
tempName = [[NSString alloc] initWithFormat: @"%@", newName];
else
tempName = [[NSString alloc] initWithFormat: @"%@+%@", tempName, newName];
}
[newName release];
}
return [tempName autorelease];
}
感謝那很多很多整潔;我沒想到,雖然你應該initwithformat使用,但沒有真正理解爲什麼 – DSDev
到'alloc'應始終以一個'初始化...'方法的調用成對的呼叫。當你調用'alloc'時,你將獲得它返回的對象的所有權,並且必須通過向對象發送'release'或'autorelease'消息來放棄所有權。這是真正有用的閱讀,或者至少脫脂,蘋果的內存管理指南,以獲得更完整的畫面:http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html – jlehr