nil 和released 对象的区别

发布于 2024-09-11 04:20:58 字数 115 浏览 5 评论 0原文

我是 Objective-C 的新手,我无法理解这一点。我知道我可以向 nil 发送消息(这是对 Objective-C 功能的大肆宣传),但我无法向已释放的对象发送消息,在这种情况下会出现异常,它们之间有什么区别?

I'm new to Objective-C and and I can't understand this. I know that I can send a message to nil (it's so hyped about feature of Objective-C), but I can't send a message to released object, getting an exception in this case, what the difference between them?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

裂开嘴轻声笑有多痛 2024-09-18 04:20:58

nil 是内存地址 0。运行时知道在发送该地址消息时不要执行任何操作,因为它是预定义的不存在的对象地址。

但是,释放的对象将是随机内存地址,因为当先前有效的对象被销毁时,指针不会被清除。由于它不是规定的不存在的对象地址,因此运行时不知道它是无效的,并且会尝试向其发送消息。这通常会立即使您的程序崩溃。

释放变量后,您可以通过将变量设置为 nil 来避免这种情况。

nil is the memory address 0. The runtime knows to not do anything when this address is messaged, because it is the predefined nonexistant object address.

However, a deallocated object will a random memory address, because the pointer isn't cleaned up when the formerly valid object is destroyed. Since it is not the prescribed nonexistant object address, the runtime doesn't know that it's invalid, and will try to send it the message. This will usually crash your program right away.

You can avoid this by setting variables to nil once you've released them.

明月松间行 2024-09-18 04:20:58

nil 是“指向无”,并且允许向 nil(无)发送消息。
对象有一个其数据所在的地址。您使用该地址发送消息并释放对象。像这样:

id myObject; // Initialized some where else
[myObject release];

然后向它​​发送一条消息,如下所示:

[myObject someMessage]; // At this point myObject != nil. Not allowed

那么您实际上是在尝试向现在释放的对象的地址发送消息。这是不允许的。

myObject = nil;
[myObject someMessage]; // Allowed

nil is 'pointing to nothing', and its allowed to send a message to nil (nothing).
An object has a address where its data resists. You use this address to send message and release the object. Like this:

id myObject; // Initialized some where else
[myObject release];

and then send it a message like this:

[myObject someMessage]; // At this point myObject != nil. Not allowed

Then you are actually trying to send a message to the address of the now released object. And this is not allowed.

myObject = nil;
[myObject someMessage]; // Allowed
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文