重新分配释放的对象可以吗?

发布于 2024-12-14 06:50:41 字数 199 浏览 2 评论 0原文

如果我这样做了,

Object * myObject = [[Object alloc]init];
[myObject release];

再次在下一行分配我的对象有什么问题吗

myObject = [[Object alloc]init];

if i did this

Object * myObject = [[Object alloc]init];
[myObject release];

is there anything wrong about allocating my object in next line

myObject = [[Object alloc]init];

again?

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

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

发布评论

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

评论(4

旧伤还要旧人安 2024-12-21 06:50:41

这样做是安全的。

原因是 myObject 不是一个对象,它是对该对象的引用(或者准确地说是指针)。这意味着您有两个完全独立的对象,但您忘记了对第一个对象的引用。

This is safe to do.

The reason is that myObject is not an object, it's a reference (or pointer if you want to be exact) to the object. That means you've got 2 completely independent objects, but you forget about the reference to the first.

一刻暧昧 2024-12-21 06:50:41

完全没问题。
[myobject release]; 释放myObject指向的对象。

稍后,myobject = [[Object alloc] init]
将使 myobject 指向另一个对象。

No problem at all.
[myobject release]; releases the object pointed at by myObject.

Later, myobject = [[Object alloc] init]
will make myobject point to another object.

娇柔作态 2024-12-21 06:50:41

这并没有什么问题。这就是确保不会泄漏第一个对象的方法。

但是,从技术上讲,您并没有再次分配已释放的对象。您只是再次使用旧指针。

Object * myObject = [[Object alloc]init];
myObject = [[Object alloc]init];

将导致泄漏您创建的第一个对象。

There is nothing wrong with that. That is how you make sure you don't leak your first object.

However, you are not technically allocating the released object again. You are just using the old pointer again.

Object * myObject = [[Object alloc]init];
myObject = [[Object alloc]init];

will result in leaking the first object you created.

万劫不复 2024-12-21 06:50:41

是的当然。这项技术在本地方法变量中特别有用,您可以通过将其重新分配为新对象来重用曾经声明过的对象..!!

yes of course. this technique is specially useful in local method variables where you can reuse the object declared once by reallocating it again as new object..!!

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