Why has NSNumber such strange retainCounts?

后端 未结 5 600
星月不相逢
星月不相逢 2020-11-28 16:36
NSNumber* n = [[NSNumber alloc] initWithInt:100];
NSNumber* n1 = n;

In the code above, why is the value of n\'s retainCount set to 2? In the second

5条回答
  •  眼角桃花
    2020-11-28 17:38

    You should never rely on the retainCount of an object. You should only use it as a debugging aid, never for normal control flow.

    Why? Because it doesn't take into account autoreleases. If an object is retained and subequently autoreleased, its retainCount will increment, but as far as you're concerned, its real retain count hasn't been changed. The only way to get an object's real retain count is to also count how many times it's been added to any of the autorelease pools in the autorelease pool chain, and trying to do so is asking for trouble.

    In this case, the retainCount is 2 because somewhere inside alloc or initWithInt:, the object is being retained and autoreleased. But you shouldn't need to know or care about that, it's an implementation detail.

提交回复
热议问题