nil 和released 对象的区别
我是 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
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.nil 是“指向无”,并且允许向 nil(无)发送消息。
对象有一个其数据所在的地址。您使用该地址发送消息并释放对象。像这样:
然后向它发送一条消息,如下所示:
那么您实际上是在尝试向现在释放的对象的地址发送消息。这是不允许的。
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:
and then send it a message like this:
Then you are actually trying to send a message to the address of the now released object. And this is not allowed.