Still learning iOS development with ObjectiveC and iOS, and trying to realy understand memory management! Appreciate any advise on the snippet below, eg:
1) Analyser says there are potential memory leaks, but can’t solve them?
2) Should I keep alloc and init the NSStrings in the for loop and when appended to?
Thanks
- (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];
}
You don’t need any of the calls to
alloc,release, orautorelease. Instead, use[NSString stringWithFormat:]to create instances ofNSStringthat you don’t own, and therefore don’t need to manage. Also, consider usingNSMutableStringto simplify your code a bit, for example along the lines of the following (untested) version: