Following the StringCalculator kata from Xcode Katas, I ended up with a following class.
@implementation StringCalculator
- (int) add: (NSString *) string {
// this is marked as a potential memory leak by the `Analyze` tool
NSMutableString *separatorCharacters = [@"\n" mutableCopy];
if ([string hasPrefix:@"//"]) {
NSRange range = NSMakeRange(2, 1);
NSString *additionalSeparator = [string substringWithRange:range];
[separatorCharacters appendString:additionalSeparator];
} else {
[separatorCharacters appendString:@","];
}
NSCharacterSet *separators = [NSCharacterSet characterSetWithCharactersInString:separatorCharacters];
NSArray *numbers = [string componentsSeparatedByCharactersInSet:separators];
// [separatorCharacters release];
int sum = 0;
for (NSString *number in numbers) {
sum += [number intValue];
}
return sum;
}
@end
Everything works fine, but when I run Analyze, I’m getting a potential memory leak on the first line of the method. If I do a manual release at the end, it seems to satisfy the analyzer, but I don’t really understand why this is happening.
How does creating a mutableCopy differ from a substringWithRange, for example? I’m not sure how to check if I’m using ARC, but if I wasn’t, I should be leaking memory on every single line where I create a object right?
I also thought that calling release is kind of deprecated or unnecessary in ARC projects.
You aren’t using ARC. Manual releasing is forbidden with ARC, this wouldn’t compile. Check your build settings.