开发者

init] in automatic reference counting

I know that I am suppose to use:

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

to initia开发者_StackOverflow社区lise 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜