我在 Xcode 4.4.1 上创建了一个空的 iOS 应用程序,并执行了以下操作:
NSNumber *n1 = @1;
NSNumber *n2 = @2;
NSNumber *n3 = @3;
NSNumber *n100 = @100;
NSString *s = @"haha";
NSArray *a = @[n1, s];
NSDictionary *d = @{ @"ha" : @1, @3 : @"hello" };
NSLog(@"retain count of @1 is %i", [n1 retainCount]);
NSLog(@"retain count of @2 is %i", [n2 retainCount]);
NSLog(@"retain count of @3 is %i", [n3 retainCount]);
NSLog(@"retain count of @100 is %i", [n100 retainCount]);
NSLog(@"retain count of @\"haha\" is %i", [s retainCount]);
NSLog(@"retain count of array literal is %i", [a retainCount]);
NSLog(@"retain count of dictionary literal is %i", [d retainCount]);
结果是:
retain count of @1 is 10
retain count of @2 is 4
retain count of @3 is 5
retain count of @100 is 1
retain count of @"haha" is -1
retain count of array literal is 1
retain count of dictionary literal is 1
所以数组字面量和字典字面量的保留计数为 1,而字符串字面量据说存在于整个应用程序的运行中,所以这就是它为 -1(可能意味着 MAX unsigned int)的原因,但@1
实际的保留计数为7、8和10在不同的时间。有规律吗?我发现我也可以这样做[n1 retain]
,[n1 release]
它会相应地增加和减少保留计数。