iosobjective-cnsnumberretaincount

Irregular retain counts of NSNumbers


I am using NSNumbers throughout my app (non-ARC) using different syntaxes. Just to be a little more informed, I tried to see how NSNumbers are retained depending on their initialization syntaxes. So I did the following:

NSNumber* a = @1;
NSNumber* b = [[NSNumber alloc] initWithInt:2];
NSNumber* c = [NSNumber numberWithInt:3];

NSLog(@"%d | %d | %d", a.retainCount, b.retainCount, c.retainCount);

This code fragment is executed with a button tap, and the output has perplexed me (repetitive taps) :

73 | 27 | 6
78 | 159 | 22
78 | 160 | 22
78 | 161 | 22
78 | 162 | 22
78 | 163 | 22
85 | 169 | 22
85 | 170 | 22
85 | 171 | 22
85 | 172 | 22

Now this does not really have a purpose (at least not in my case), but I would like to know how these NSNumbers get to these retain counts.


Solution

  • You should never use retainCount. NEVER. look here