Cemre Mengü
Cemre Mengü

Reputation: 18754

Objective C @autoreleasepool directive

I am reading a book which says (if I am not getting it wrong) wrapping some code with @autoreleasepool statement enables the ARC. First of all is this the case ?

My second concern is when I am doing some iOS example programs, although I enable ARC when creating a new project, I never see this directive being used anywhere (in the automatically generated code). Does this mean that ARC is not being used ? Any ideas/pointers is appreciated.

Upvotes: 3

Views: 477

Answers (4)

Eric
Eric

Reputation: 1678

My second concern is when I am doing some iOS example programs, although I enable ARC when creating a new project, I never see this directive being used anywhere (in the automatically generated code). Does this mean that ARC is not being used ? Any ideas/pointers is appreciated.

You application does use this. Check out the main.m file in your project. You will find it there.

Upvotes: 2

kubi
kubi

Reputation: 49354

First off, the book is wrong. @autoreleasepool is orthogonal to ARC. You can use autoreleasepools without ARC and you can use ARC without autoreleasepools (but you shouldn't).

Secondly, the main thread of a project created using any of Xcode's default projects will have the autoreleasepool pool created for you. Any thread you create will need to create its own autorelease pool.

Upvotes: 4

DrummerB
DrummerB

Reputation: 40211

@autoreleasepool doesn't "enable" ARC. It's just the ARC way to use autorelease pools.

Before ARC, you used the NSAutoreleasePool class to set up an autorelease pool like this:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Code benefitting from a local autorelease pool.
[pool release];

But you're not allowed to call release when using ARC, so instead a new way to use autorelease pools was introduced:

@autoreleasepool {
    // Code benefitting from a local autorelease pool.
}

@autoreleasepool blocks are more efficient than using an instance of NSAutoreleasePool directly; you can also use them even if you do not use ARC.

Upvotes: 4

user529758
user529758

Reputation:

wrapping some code with @autoreleasepool statement enables the ARC

No. ARC is enabled by a compiler flag. @autoreleasepool is just a keyword used to create autorelease pools even if you're using ARC (because normally you would create and destroy them using alloc-init and release, respectively, but you can't send explicit release messages under ARC - that's why this keyword had been introduced.)

And if you enable ARC in Xcode/with the compiler/etc, it's enabled. Certainly, there are better solutions than the "autorelease everything" principle and that may be the cause of you not encountering this keyword in example code.

Upvotes: 2

Related Questions