문제

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.

도움이 되었습니까?

해결책

You should never use retainCount. NEVER. look here

다른 팁

In Objective-C, retainCount is the number which controls the lifespan of an object. The object remains alive until the retainCount turns 0, and then the object gets deallocated. This is the big picture, with many exceptions, but this is the rule that applies here.

Those retain counts mean that those numbers are used somewhere in your application. Some other objects have retained them. Since your own code does not, this means that some other system objects do.

We'll profile your application with the "Allocation" instrument, and see what it can tell us. Here is the code we'll run:

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

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

[[[UIAlertView alloc] initWithTitle:@"number b"
                            message:[NSString stringWithFormat:@"address: %p, retainCount: %d", b, b.retainCount] delegate:nil
                  cancelButtonTitle:nil
                  otherButtonTitles:nil] show];

This alert will tell us what is the address of the number. Instrument will let us track this object's life.

Let's choose the Debug configuration in the profile setup of our scheme. Let's check the "Record reference count" in the "Allocations" instrument options. And see what we can get.

enter image description here

enter image description here

See? This number is indeed used by many system frameworks. Now you know why it has such a big retain count :-)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top