为什么我的对象仍然工作后无数的版本? [英] Why does my object still work after countless releases?

查看:83
本文介绍了为什么我的对象仍然工作后无数的版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我永远似乎不会释放我的 NSMutableString ,如下所示。初始保留计数应该为1,但是在发布几次后,字符串仍然可用,就像没有发生任何事情!

I can never seem to deallocate my NSMutableString as shown below. The initial retain count should be 1, but after releasing several times, the string is still usable like nothing happened!

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // insert code here...
    NSMutableString* s = [[NSString alloc]initWithString:@"AAA"];
    [s release];
    [s release];
    [s release];
    [s release];
    [s release];

    NSLog(@"%@",s);

    [pool drain];
    return 0;
}

当然,如果我使用Analyze它仍然告诉我,第二个释放

Of course, if I use Analyze it still tells me that I release a released object on the second release.

推荐答案

释放对象它可以 销毁对象,至少在你所关心的地方,但它不需要立即销毁对象:在你的第一个 [s release] ,Cocoa可以随意使用以前由 s 使用的内存。它可能会给下一个执行 alloc 的对象赋予该内存,在这种情况下,您以后尝试访问 s 导致一个火热的运行时崩溃...或者它可能不需要该内存马上,在这种情况下你可能会离开访问一个释放的对象。

Releasing an object tells the runtime that it can destroy the object, at least as far as you're concerned, but it doesn't require that the object be destroyed immediately: After your first [s release], Cocoa is free to do whatever it pleases with the memory formerly used by s. It might give that memory to the next object that does an alloc, in which case your later attempts to access s will result in a fiery runtime crash… or it might not need that memory right away, in which case you might get away with accessing a released object.

经验法则少我已经释放这个对象,这意味着它不再存在和更多我已经释放这个对象,这意味着它不再保证存在。

The rule of thumb is less "I've released this object, which means it no longer exists" and more "I've released this object, which means it's no longer guaranteed to exist."

这篇关于为什么我的对象仍然工作后无数的版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆