15

If I have this code,

+ (MyCustomClass*) myCustomClass
{
    return [[[MyCustomClass alloc] init] autorelease];
}

This code guarantees the returning object is autoreleased. What's the equivalent of this in ARC?

eonil
  • 83,476
  • 81
  • 317
  • 516

2 Answers2

20

There is no equivalent in ARC, as you don't need to do it yourself. it will happen behind the scenes and you are not allowed to do it your self.

You simply use -

+ (MyCustomClass*) myCustomClass
{
    return [[MyCustomClass alloc] init];
}

I suggest you to watch the ARC introduction in the 2011 WWDC as it very simple when you get it.

Look here: https://developer.apple.com/videos/wwdc/2011/

And as the guy in the movie says -

You don't have to think about it any more (almost)

shannoga
  • 19,649
  • 20
  • 104
  • 169
  • 4
    Note that what happens depends on how you name your method, though. – Thilo Nov 28 '11 at 06:09
  • 1
    That is trow and thats why I added the almost in the last line. I truly think that the WWDC lecture is great and explains all the main issues with ARC. – shannoga Nov 28 '11 at 07:15
  • 1
    Maybe I have to know every details what happening in underneath because of that *almost* :) – eonil Dec 03 '11 at 00:53
7

When compiling with ARC, you simply write it as:

+ (MyCustomClass *)myCustomClass
{
    return [[MyCustomClass alloc] init];
}

and the compiler/runtime will handle the rest for you.

justin
  • 104,054
  • 14
  • 179
  • 226
  • the runtime has nothing to do with ARC, it's all compiler magicness – DanZimm Nov 28 '11 at 14:12
  • @DanZimm no - the runtime is also at work. for example: it is the runtime that allows ownership of objects to be transferred across frames. http://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime – justin Nov 29 '11 at 05:41
  • right but when arc support was added the runtime wasn't changed, those functions existed already - note im referring to when apple began supporting arc – DanZimm Nov 30 '11 at 01:58