neb*_*ebs 5 memory-management objective-c
我正在查看其他人的代码并注意到他们在他们不拥有的NSString上调用了'release'(从未在任何地方调用alloc/retain/copy而且它不是属性).
这对我来说有点奇怪,如果你对一个你不"拥有"或者其引用数已经为0的对象调用'release',我会想知道是否会出现任何奇怪的行为?下面的代码编译/运行没有警告,所以我猜测没有问题,但我只是好奇.
// 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 = ?
Run Code Online (Sandbox Code Playgroud)
Ben*_*tto 15
是的,不要那样做.您的评估是正确的,您对所有权规则的理解也是正确的.向已发布的对象发送消息具有未定义的行为 - 有时您会因为其他事情发生而变得幸运,并且不会发生任何事情.有时候你会立即崩溃,有时候会因为你已经损坏了别的东西而崩溃了.