Pragma to explicitly enable ARC?

2019-01-18 12:40发布

问题:

Is there a #pragma (or otherwise some construct) to explicitly enable automatic reference counting (ARC) in an Objective-C (or Objective-C++) source file? Even better if the source file can cause compilation to fail if ARC is not enabled.

I'm starting to have a number of ARC-only source files that can be potentially shared with other projects. Most of these contain category methods to extend built-in classes. I just don't want to accidentally include these in a non-ARC project and starts leaking out memory.

Thanks in advance!

回答1:

As far as I can tell there is no way to explicitly enable or disable ARC.

However it is possible to detect if it is enabled. Simply add the following snippet to any file that requires ARC.

#ifndef __has_feature
  #define __has_feature(x) 0 /* for non-clang compilers */
#endif

#if !__has_feature(objc_arc)
  #error ARC must be enabled!
#endif

More info:
http://clang.llvm.org/docs/AutomaticReferenceCounting.html
http://clang.llvm.org/docs/LanguageExtensions.html#__has_feature_extension