代码示例:为什么我仍然可以访问此NSString对象后,我已经释放它? [英] Code Example: Why can I still access this NSString object after I've released it?

查看:102
本文介绍了代码示例:为什么我仍然可以访问此NSString对象后,我已经释放它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是写了一些探索性代码来巩固我对Objective-C的理解,我遇到了这个我不太明白的例子。我定义这个方法并运行代码:

I was just writing some exploratory code to solidify my understanding of Objective-C and I came across this example that I don't quite get. I define this method and run the code:

- (NSString *)stringMethod
{
    NSString *stringPointer = [[NSString alloc] initWithFormat:@"string inside stringPointer"];
    [stringPointer release];
    [stringPointer release];
    NSLog(@"retain count of stringPointer is %i", [stringPointer retainCount]);
    return stringPointer;
}

运行代码并调用此方法后,我注意到以下几点: / p>

After running the code and calling this method, I notice a few things:


  1. 通常情况下,如果我尝试访问一些在零保留计数后应该被释放的东西,我会得到一个EXC_BAD_ACCESS错误。在这里,我得到一个malloc双自由错误。为什么呢?

  1. Normally, if I try to access something that's supposedly dealloced after hitting zero retain count, I get a EXC_BAD_ACCESS error. Here, I get a malloc "double free" error instead. Why is that?

无论我将多少行[stringPointer release]添加到代码中,NSLog报告保留计数为1。添加更多的版本我只是得到更多的双免费错误。为什么发布语句不能正常工作?

No matter how many lines of "[stringPointer release]" I add to the code, NSLog reports a retain count of 1. When I add more releases I just get more "double free" errors. Why aren't the release statements working as expected?

虽然我已经过度发布了stringPointer, ,返回值仍然工作,好像没有发生(我有另一个NSLog在主要代码报告返回值)。程序继续正常运行。再次,有人可以解释为什么会发生这种情况吗?

Although I've over-released stringPointer and I've received a bunch of "double free" errors, the return value still works as if nothing happened (I have another NSLog in the main code that reports the return value). The program continues to run normally. Again, can someone explain why this happens?

这些例子相当微不足道,完全掌握发生了什么。谢谢!

These examples are fairly trivial, but I'm trying to get a full grasp of what's going on. Thanks!

推荐答案

你得到一个双重的免费错误,因为你释放两次,导致两个dealloc消息。 = P

You're getting a double free error because you are releasing twice and causing two dealloc messages. =P

请记住,只是因为释放并不意味着其内存地址上的数据立即被销毁。它只是被标记为未使用,所以内核知道,在未来的某个时候,它是免费的用于另一个数据。直到那一点(在你的应用程序空间中是完全不确定的),数据将保留在那里。

Keep in mind that just because you release doesn't doesn't mean the data at its memory address is immediately destroyed. It's just being marked as unused so the kernel knows that, at some point in the future, it is free to be used for another piece of data. Until that point (which is totally nondeterministic in your app space), the data will remain there.

再次:release(和dealloc'ing)数据破坏在字节级别。它只是内核的标记。

So again: releasing (and dealloc'ing) doesn't necessitate immediate data destruction on the byte level. It's just a marker for the kernel.

这篇关于代码示例:为什么我仍然可以访问此NSString对象后,我已经释放它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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