init] in automatic reference counting

天大地大妈咪最大 提交于 2019-12-05 04:51:47

问题


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


回答1:


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:

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

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.

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

To clarify:

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.    

For ARC, you just do this:

realObject = [[ObjectClass alloc] init];



回答2:


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 insert retain and release calls for you.



来源:https://stackoverflow.com/questions/6482635/init-in-automatic-reference-counting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!