iOS Memory Management & NSString Initialisation
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 memo开发者_如何转开发ry 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
, or autorelease
. Instead, use [NSString stringWithFormat:]
to create instances of NSString
that you don't own, and therefore don't need to manage. Also, consider using NSMutableString
to simplify your code a bit, for example along the lines of the following (untested) version:
- (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;
}
You have 2 alloc initWithFormat for tempName. One before the loop and one within the loop.
Use ARC (Automatic Reference Counting) for new projects. For older projects it may be easy to convert them, if not ARC can be disabled on a file-by-file basis where necessary.
Using a mutable string, autoreleased convience methods and a little rerfactoring:
- (NSString *) lookUpCharNameForID: (NSString *) inCharID
{
NSMutableString *tempName = [NSMutableArray array];
if (inCharID.length)
{
NSArray *idList = [inCharID componentsSeparatedByString: @","];
for (NSString *nextID in idList)
{
if (tempName.length == 0)
[tempName appendFormat: @"%@C", nextID];
else
[tempName appendFormat: @"+%@C", nextID];
}
}
return tempName;
}
精彩评论