仍在使用 ObjectiveC 和 iOS 学习 iOS 开发,并试图真正了解内存管理!感谢对以下代码段的任何建议,例如: 1) Analyzer说有潜在的内存泄漏,但无法解决? 2) 我应该在 for 循环中保留 alloc 并初始化 NSStrings 吗?
谢谢
- (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];
}
最佳答案
您不需要对 alloc
、release
或 autorelease
的任何调用。相反,使用 [NSString stringWithFormat:]
来创建您不拥有的 NSString
实例,因此不需要管理。此外,考虑使用 NSMutableString
来稍微简化您的代码,例如按照以下(未经测试的)版本:
- (NSString *) lookUpCharNameForID: (NSString *) inCharID
{
NSMutableString *tempName = nil;
if (![inCharID isEqualToString: @""])
{
NSArray *idList = [inCharID componentsSeparatedByString: @","];
for (NSString *nextID in idList)
{
[tempName appendString:@"+"]; // Does nothing if tempName is nil.
if (tempName == nil)
tempName = [NSMutableString string];
[tempName appendFormat:@"C%@", nextID];
}
}
return tempName;
}
关于iOS 内存管理和 NSString 初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7573926/