仍在学习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