很多关于 NSString 引用计数的问题

Lots of Problems About NSString Reference Count

我在 Objective-C 中进行了一些关于 Mannul 引用计数的测试。 我 运行 这些代码如下:

- (void) test {
    NSData *a1 = [[NSData alloc] init];
    NSLog(@"NSData: %lu", [a1 retainCount]);

    NSMutableData *a2 = [[NSMutableData alloc] init];
    NSLog(@"NSMutableData: %lu", [a2 retainCount]);

    NSObject *a3 = [[NSObject alloc] init];
    NSLog(@"NSObject: %lu", [a3 retainCount]);

    NSString *b1 = [[NSString alloc] initWithFormat: @"%@", @"ok"];
    NSLog(@"NSString: %lu", [b1 retainCount]);


    NSString *b2 = [[NSString alloc] initWithFormat: @"%@", a3];
    NSLog(@"NSStinrg: %lu", [b2 retainCount]);


    NSString *a = @"abc";
    NSString *b = @"abc";
    NSLog(@"%p", a);
    NSLog(@"%p", b);

}

控制台:

2016-06-23 16:15:50.490 text[38147:3406036] NSData: 18446744073709551615
2016-06-23 16:15:50.491 text[38147:3406036] NSMutableData: 1
2016-06-23 16:15:50.491 text[38147:3406036] NSObject: 1
2016-06-23 16:15:50.491 text[38147:3406036] NSString: 18446744073709551615
2016-06-23 16:15:50.491 text[38147:3406036] NSStinrg: 1
2016-06-23 16:15:50.491 text[38147:3406036] 0x10359d160
2016-06-23 16:15:50.491 text[38147:3406036] 0x10359d160

而且我想知道为什么NSDataNSString的引用计数是UINT_MAX(-1),而initWithFormat会让b2加计数?为什么ab的地址一样?

非常感谢。

空的不可变 NSData 对单个实例是唯一的,不能保留或释放(由 UINT_MAX-1 refcount 表示)。对于 NSString 来说,%@ 被对象上调用 -description 的结果和 NSString returns self 的 -description 方法所取代。所以你在那里得到一个常量 NSString 文字,这同样不是可以保留或释放的东西。常量字符串也是唯一的,因此在编译时只有一个嵌入到您的二进制文件中,并且不进行任何分配。

来自apple docs

- (NSUInteger)retainCount

This method is of no value in debugging memory management issues. Because any number of framework objects may have retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number of deferred releases on an object, it is very unlikely that you can get useful information from this method.