init] 自动引用计数
我知道我应该使用:
ObjectClass *tmpObject = [[ObjectClass alloc] init];
realObject = tmpObject;
[tmpObject release]
初始化realObject
(其中realObject
是类中的一个对象)
但是现在使用ARC模式,释放是自动的,我还需要吗使用这种技术? 我可以简单地使用realObject = [[ObjectClass alloc] init];
吗? 如果没有的话,有什么具体原因会泄漏吗?
谢谢
I know that I am suppose to use:
ObjectClass *tmpObject = [[ObjectClass alloc] init];
realObject = tmpObject;
[tmpObject release]
to initialise realObject
(where realObject
is an object within a class)
But now with ARC mode, releasing is automatic, do i still need to use this technique?
Can I simply use realObject = [[ObjectClass alloc] init];
?
If not is there any specific reason why it would leak?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 Spencer 所说,如果您在启用 ARC 的情况下进行编译,则根本无法调用
release
。这样做是错误的,编译器会为您解决这个问题。然而:
在这种情况下,tmpObject 对于 ARC 和手动保留释放来说是完全没有意义的。事实上,在手动保留释放中,上面的代码将立即释放分配的对象,导致它被释放(除非
ObjectClass
内部做了一些奇怪的事情)和realObject
将留下一个悬空指针。也就是说,当有人第一次尝试向
realObject
发送消息时,所编写的代码将导致崩溃。澄清一下:
对于 ARC,你只需这样做:
As Spencer said, if you compile with ARC enabled, you cannot call
release
at all. It is an error to do so and the compiler takes care of it for you.However:
The
tmpObject
in that case is entirely pointless for both ARC and manual retain-release. And, in fact, in manual retain-release, the above code will immediately release the object allocated, causing it to be deallocated (unlessObjectClass
internally does something odd) andrealObject
will be left with a dangling pointer.I.e. that code, as written, will cause a crash the first time anyone tries to message
realObject
.To clarify:
For ARC, you just do this:
如果您使用 -fobjc-arc 进行编译(即使用 ARC),那么您不仅不需要调用
release
,如果这样做还会出现编译器错误。使用 ARC 时,编译器的工作就是为您插入retain
和release
调用。If you are compiling with -fobjc-arc (ie, using ARC) then not only do you not need to call
release
, it is a compiler error if you do so. When using ARC, it is the job of the compiler to insertretain
andrelease
calls for you.