Why has NSNumber such strange retainCounts?

后端 未结 5 606
星月不相逢
星月不相逢 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:20

    Retain counts are an implementation detail. They can be kindasorta useful in debugging, sometimes, but in general you should not care about them. All you should care about is that you're following the memory management rules.

    For an example of why looking at retain counts is unreliable, this is a perfectly legal class that obeys the API contract and will behave correctly in all circumstances:

    @implementation CrazyClass
      - (id)retain {
          for(int i=0; i<100; i++) {
              [super retain];
          }
      }
    
      - (void)release {
          for(int i=0; i<100; i++) {
              [super release];
          }
      }
    @end
    

    …but if you inspected its retain count, you'd think you had an "issue."

    This precise case doesn't happen too often in practice, but it illustrates why looking at retain counts is useless for telling if something is wrong. Objects do get retained behind the scenes by code outside of your control. NSNumber, for example, will sometimes cache instances. Objects get autoreleased, which isn't reflected in the retain count. Lots of things can happen that will confuse the retain count. Some classes might not even keep their retain counts where you can see them.

    If you suspect you have a leak, you should check with the real debugging tools meant for that purpose, not by poking at retain counts. And for code you're writing, you should primarily be concerned with following the guidelines I linked above.

提交回复
热议问题