本文介绍了init]中的自动引用计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我应该使用:

ObjectClass *tmpObject = [[ObjectClass alloc] init];
realObject = tmpObject;
[tmpObject release]

初始化 realObject (其中 realObject 是类中的对象)

to initialise realObject (where realObject is an object within a class)

但是现在使用ARC模式,释放是自动的,我仍然需要使用此技术吗?
我可以简单地使用 realObject = [[ObjectClass alloc] init]; 吗?
如果没有,则有任何特定原因导致它泄漏吗?

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?

谢谢

推荐答案

正如Spencer所说,如果在启用ARC的情况下进行编译,则根本无法调用 release 。这样做是错误的,编译器会为您处理。

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.

但是:

ObjectClass *tmpObject = [[ObjectClass alloc] init];
realObject = tmpObject;
[tmpObject release]

tmpObject 在这种情况下,对于ARC和手动保留释放都是毫无意义的。而且,实际上,在手动保留释放中,上面的代码将立即释放分配的对象,从而导致对象被释放(除非 ObjectClass 在内部执行某些操作)和 realObject 将留下一个悬空的指针。

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 (unless ObjectClass internally does something odd) and realObject will be left with a dangling pointer.

即所写的代码将在任何人尝试向 realObject 发送消息时导致崩溃。

I.e. that code, as written, will cause a crash the first time anyone tries to message realObject.

ObjectClass *tmpObject = [[ObjectClass alloc] init];
// tmpObject now contains a reference to an instance of ObjectClass; say, 0x12340
realObject = tmpObject;
// realObject now contains a reference to that same instance; realObject == 0x12340
[tmpObject release]
// this releases the object
// both tmpObject and realObject now reference a deallocated object; much hilarity ensues.






对于ARC,您只需执行以下操作:


For ARC, you just do this:

realObject = [[ObjectClass alloc] init];

这篇关于init]中的自动引用计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-01 13:17