为什么自动释放对象还活着?
我已经创建了自动释放池。 localString 已添加到此池中。我释放了池子。 localString 和 string 必须被释放。但实际上他们还活着。你可以看到我的日志:
Why is the string object still alive? I don't know.
和代码:
-(NSString*) happyString
{
NSString *localString = [[[NSString alloc] initWithString:@"I don't know."] autorelease];
return localString;
}
-(IBAction) onButton:(id)sender
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *string = [self happyString];
[pool release];
NSLog(@"Why is the string object still alive? %@", string);
}
I've created autorelease pool. localString has added to this pool. I released the pool. localString and string must be deallocated. But in reality they are still alive. You can see my log:
Why is the string object still alive? I don't know.
and code:
-(NSString*) happyString
{
NSString *localString = [[[NSString alloc] initWithString:@"I don't know."] autorelease];
return localString;
}
-(IBAction) onButton:(id)sender
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *string = [self happyString];
[pool release];
NSLog(@"Why is the string object still alive? %@", string);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
字符串(
NSString
实例和使用@""
静态分配的字符串)在 Cocoa 中是不可变的,因此当您尝试从静态分配的,NSString
类可以进行优化:不会创建新的NSString
实例(调用-alloc
时创建的对象是立即发布),以及对您的参考返回静态分配的字符串。也就是说,这一行:实际上相当于:(
如果你检查这两个对象的内存地址,你会发现它们是相同的。)
由于这种类型的字符串无法释放,因此它不会在您期望它消失时消失。
如果您以无法优化的方式创建字符串,例如:
那么您的代码将按照您的预期运行,并且您的应用程序(希望)将在您的
NSLog
行崩溃。Strings (
NSString
instances and statically allocated strings with@""
) are immutable in Cocoa, so when you try to create a newNSString
from a statically allocated one, theNSString
class can make an optimisation: a newNSString
instance is not created (the object created when you called-alloc
is immediately released), and the reference to your statically allocated string is returned. That is, the line:Is actually equivalent to:
(If you check the memory addresses of those two objects, you can see that they are the same.)
As this type of string cannot be released, it does not disappear when you expect it to.
If you were to create your string in a way that cannot be optimised, for example:
Then your code will behave as you expect, and your application will (hopefully) crash at your
NSLog
line.如果您尝试过
NSString
之外的任何类(任何自定义类),那么它就不会存在。If you have tried any classes (any custom classes) other than
NSString
, then it would not be alive..