‘autorelease is unavailable’ errors and ‘ARC forbids explicit message send of autorelease’ errors

Question:

    I build a project with ARC and import some previous work files (those are non arc, MRC), how could I make it build successfully.

Answer:

 Since the file is either compiled as ARC, you can either remove the autorelease message or disable ARC for the single file. 

 Here, I will show you how to disable ARC for the single file.

 Disable ARC for individual files by adding the -fno-objc-arc compiler flag for those files.

You add compiler flags in Targets -> Build Phases -> Compile Sources. You have to double click on the right column of the row under Compiler Flags. You can also add it to multiple files by holding the cmd button to select the files and then pressing enter to bring up the flag edit box.

xcode

Analysis: 

ARC is enabled per translation — every compiled source file and everything it sees via inclusion must abide by the ARC or MRC. And yes, the modes can coexist (i.e. you can have ARC on for some files, but not all and the libraries you link to can use either).
You have two modes:
ARC
The expression [obj autorelease] is forbidden. ARC will add it for you (unless you have unusual reference counting sequences).
Under typical scenarios, you can just write:
// a method which returns an autoreleased object - (NSArray *)something { return [[NSArray alloc] initWithObjects:…YOUR_OBJECTS…]; }
and then ARC will add the autorelease for you.
But if you write:
- (NSArray *)something { return [[[NSArray alloc] initWithObjects:…YOUR_OBJECTS…] autorelease]; }
in ARC, it will be a compile error (like the one in your title).
MRC
And this is the MRC form:
- (NSArray *)something { return [[[NSArray alloc] initWithObjects:…YOUR_OBJECTS…] autorelease]; }

Your project probably uses ARC by default (i.e. it is defined in an xcconfig, at the project level, or at the target level), though you have added a source file which was written for MRC.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s