【发布时间】:2010-06-18 16:02:46
【问题描述】:
我正在查看其他人的代码,并注意到他们在他们不拥有的 NSString 上调用了“release”(从未在任何地方调用 alloc/retain/copy,它不是属性)。
这对我来说有点奇怪,它让我想知道如果你对一个你不“拥有”或引用计数已经为 0 的对象调用“释放”,是否会发生任何奇怪的行为?下面的代码编译/运行良好,没有警告,所以我猜没有问题,但我只是好奇。
// Releasing an object I don't own
NSString *notMyString = [NSString stringWithString:@"Not mine."];
[notMyString release]; // Ignored?
// Releasing an object I own, twice
NSString *myString = [[NSString alloc] initWithString:@"Mine."];
[myString release]; // Ref count = 0
[myString release]; // Ref count = ?
【问题讨论】:
-
代码“工作”的原因是因为 NSString 的 -initWithString: 识别传入的字符串是一个常量字符串,因此不需要重新分配。由于常量字符串有效地忽略了保留/释放,因此代码的工作方式很巧合。
标签: objective-c memory-management