重新分配释放的对象可以吗?
如果我这样做了,
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这样做是安全的。
原因是
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.完全没问题。
[myobject release];
释放myObject
指向的对象。稍后,
myobject = [[Object alloc] init]
将使
myobject
指向另一个对象。No problem at all.
[myobject release];
releases the object pointed at bymyObject
.Later,
myobject = [[Object alloc] init]
will make
myobject
point to another object.这并没有什么问题。这就是确保不会泄漏第一个对象的方法。
但是,从技术上讲,您并没有再次分配已释放的对象。您只是再次使用旧指针。
将导致泄漏您创建的第一个对象。
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.
will result in leaking the first object you created.
是的当然。这项技术在本地方法变量中特别有用,您可以通过将其重新分配为新对象来重用曾经声明过的对象..!!
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..!!