I’m trying to get my head around memory management in Objective – C. I’ve used the garbage collector up until this point but before I go forward I’d like to get a better understanding of manually managing memory. I’m aware that I don’t have an implementation of a dealloc method in this code.
My question is why does my inputString variable have a retain count of eleven here?
#import "AppController.h"
@implementation AppController
-(id) init
{
[super init];
NSLog(@"init");
speechSynth = [[NSSpeechSynthesizer alloc] initWithVoice:nil];
NSLog(@"speechSynth retain count is %d",[speechSynth retainCount]);
return self;
}
-(IBAction) count:(id) sender
{
NSString *outputString;
int numberOfCharacters;
inputString = [textField stringValue];
numberOfCharacters = [inputString length];
outputString = [NSString stringWithFormat:@"\"%@\" has %d characters",inputString,numberOfCharacters];
[label setStringValue:outputString];
[speechSynth startSpeakingString:outputString];
NSLog(@"outputString retain count is : %i",[outputString retainCount]);
NSLog(@"inputString retain count is: %d",[inputString retainCount]);
NSLog(@"speechSynth retain count is: %d",[speechSynth retainCount]);
[outputString release];
}
@end
Apple’s answer is “it doesn’t matter.” Track your references properly and let the runtime sort out the rest.
Internally, the runtime may be giving you a pointer to a singleton empty string (since NSStrings are immutable). Or it may be doing something else. But the reasoning behind a reference count for a variable that from your perspective has just been allocated is considered to be runtime internals, and you shouldn’t rely on it for anything.
Use Instruments and zombie objects to figure out if you’re leaking or over-releasing, and pretend that the retainCount message doesn’t exist.