为什么@ 1的保留计数等于7、8或10? [英] Why is the retain count of @1 equal to 7, 8 or 10?
问题描述
我在Xcode 4.4.1上创建了一个空的iOS应用,并执行了以下操作:
I created an empty iOS app on Xcode 4.4.1, and did the following:
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]
,它会相应增加和减少保留计数.
so the retain count of array literal and dictionary literal is 1, and string literal is said to exist for the whole app's running, so that's why it is -1 (probably meaning MAX unsigned int), but the retain count of @1
actually come out as 7, 8, and 10 at different times. Is there a rule to it? I found that I can do [n1 retain]
and [n1 release]
as well, and it will increase and decrease the retain count accordingly.
推荐答案
我认为这表明了原因:每次遇到@1
时,它都类似于[[[NSNumber alloc] initWithInt:1] autorelease]
,并且看起来返回的是相同的目的.因此,当完成以下操作时:
I think this points to the reason why: every time @1
is encountered, it is something like [[[NSNumber alloc] initWithInt:1] autorelease]
, and it appears that it returns the same object. So when the following is done:
NSMutableArray *arr = [[NSMutableArray alloc] init];
for (int i = 0; i < 300; i++) {
[arr addObject:@1];
}
保留数实际上变为610.如果执行以下操作,则保持不变:
the retain count actually becomes 610. And it is the same if the following is done:
NSMutableArray *arr = [[NSMutableArray alloc] init];
for (int i = 0; i < 300; i++) {
[arr addObject:[[[NSNumber alloc] initWithInt:1] autorelease]];
}
(更新:为610,因为使用@1
将保留计数增加1,并且将其保留在数组中的另一个时间,因此总计为600倍).这表明在任何地方使用@1
都会增加保留计数,并且此NSNumber对象可能会以相同的次数放置在自动释放池中.
(Update: it is 610, because the retain count is increased by 1 by the usage of @1
, and another time when it is retained by the array, so it is 600 times total). It suggests that any usage of @1
any where will increase the retain count, and this NSNumber object is probably placed in the autorelease pool the same equal number of times.
这篇关于为什么@ 1的保留计数等于7、8或10?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!