init] in automatic reference counting

倾然丶 夕夏残阳落幕 提交于 2019-12-03 21:16:37

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];

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.

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