search

Home  >  Q&A  >  body text

objective-c - [[NSDictionary alloc] init]后引用计数是几

NSDictionary *dictA =[[NSDictionary alloc] initWithObjectsAndKeys:@"1",@"two", nil];
NSLog(@"dictA retain count is %d",[dictA retainCount]);
    
    
NSDictionary *dictB =[[NSDictionary alloc] init];
NSLog(@"dictB retain count is %d",[dictB retainCount]);

问:NSLog出来分别是几?为什么?

黄舟黄舟2769 days ago451

reply all(1)I'll reply

  • 黄舟

    黄舟2017-04-21 10:59:37

    First, two outputs, the first should be 1 and the second should be . . . No, it's usually larger than 1 anyway.
    The reason is this:
    After you initialize an NSDictionary instance, the instance is immutable, which means that once it is generated, the information in the memory is fixed. In order to save memory, Objective-C will point all such immutable pointers of the same instance to the same memory. Therefore, when you dictB initializes an empty NSDictionary, it does not actually create a new instance, but points to an existing instance in history, and the RC of this instance is increased by 1.
    It seems that the first object you created with dictA will not have duplicate objects, so it is a new instance. If you do this

    NSDictionary *dictC =[[NSDictionary alloc] initWithObjectsAndKeys:@"1",@"two", nil];
    NSLog(@"dictC retain count is %d",[dictC retainCount]);

    Then this should be 2 when printed, which is RC + 1 of dictA.

    Correspondingly, Mutable instances will not have this situation. Every time they are created, it is a new instance, because it can change at any time during the life cycle.

    reply
    0
  • Cancelreply