I'm working my way through Stephen Kochan's Programming in Objective-C right now, and I've just finished Chapter 17 on memory management. The first exercise is to write a program to determine the effect on reference counts of adding and removing objects in a dictionary object. Anyway, I've got the following code:
When I compile and run it, I get the following:
num1 retain count before dictionary: 2
string1 retain count before dictionary: 1
num2 retain count before dictionary: 2
string2 retain count before dictionary: 1
num3 retain count before dictionary: 2
string3 retain count before dictionary: 1
Can anyone tell me why the NSNumber objects have a reference count of 2 after creation, while the strings only have a count of 1? I expected both types of objects to have a reference count of 1 after initialization.
Code:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSNumber *num1, *num2, *num3;
NSString *string1, *string2, *string3;
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity: 3];
num1 = [NSNumber numberWithInt: 1];
num2 = [NSNumber numberWithInt: 2];
num3 = [NSNumber numberWithInt: 3];
string1 = [NSString stringWithString: @"first string"];
string2 = [NSString stringWithString: @"second string"];
string3 = [NSString stringWithString: @"third string"];
printf("\n num1 retain count before dictionary: %x\n", [num1 retainCount]);
printf("string1 retain count before dictionary: %x\n", [string1 retainCount]);
printf(" num2 retain count before dictionary: %x\n", [num2 retainCount]);
printf("string2 retain count before dictionary: %x\n", [string2 retainCount]);
printf(" num3 retain count before dictionary: %x\n", [num3 retainCount]);
printf("string3 retain count before dictionary: %x\n", [string3 retainCount]);
[pool release];
return 0;
}
When I compile and run it, I get the following:
num1 retain count before dictionary: 2
string1 retain count before dictionary: 1
num2 retain count before dictionary: 2
string2 retain count before dictionary: 1
num3 retain count before dictionary: 2
string3 retain count before dictionary: 1
Can anyone tell me why the NSNumber objects have a reference count of 2 after creation, while the strings only have a count of 1? I expected both types of objects to have a reference count of 1 after initialization.