【问题标题】:Macro to know whether ARC enabled or not in Xcode 4.3.2宏来了解 Xcode 4.3.2 中是否启用了 ARC
【发布时间】:2012-06-07 10:39:17
【问题描述】:

在同一个文件中,我们要编写支持 ARC 和非 ARC 的代码。为此需要一些宏。

#ifdef ARC_ENABLED 
NSLog(@" ARC enabled ");
#else
NSLog(@" ARC disabled ");
[self release];
#endif

如何实现这个宏,有什么可用的宏吗? 请告诉我。先谢谢支持 注意:ARC_ENABLED 只是我写的例子

【问题讨论】:

标签: ios objective-c cocoa xcode4


【解决方案1】:

有一个客观的C宏__has_feature,你可以用它来检查arc是否启用。

来自Clang Language Extension documentation

自动引用计数

Clang 提供对自动引用计数的支持 Objective-C,无需手动 保留/释放/自动释放消息发送。有两个功能宏 与自动引用计数相关: __has_feature(objc_arc) 表示自动化的可用性 一般引用计数,而__has_feature(objc_arc_weak) 表示自动引用计数还包括支持 __weak 指向 Objective-C 对象的指针。

Feature checking macro's 部分非常好读。

你可以这样使用它..

#if !__has_feature(objc_arc)
    //Do manual memory management...
#else
    //Usually do nothing...
#endif

代码部分厚颜无耻地抄自this answer

【讨论】:

  • @Krishnabhadra,如何定义 has_feature(objc_arc),我做了类似下面的事情 #ifndef __has_feature #define __has_feature(x) 0 #endif #ifndef __has_extension #define __has_extension __has_feature // 兼容性3.0 之前的编译器。 #endif #if __has_feature(objc_arc) && __clang_major >= 3 #define ARC_ENABLED 1 #else #define ARC_ENABLED 0 #endif // __has_feature(objc_arc) 但是好像不行,我用retain and release when我在项目中启用了 ARC,出现错误
  • +1 很好的答案。 __has_feature 是一个很棒的宏,不仅可以用于 ARC,还可以用于检查很多 Objective-C 特性(例如模块)。
【解决方案2】:

以下将定义 USING_ARCUSING_MRCUSING_GC 为 0 或 1,以及一些健全性检查:

// Utility macros (undefined below)

#define PREFIX_ONE(a) 1##a
#define EMPTY_DEFINE(a) (PREFIX_ONE(a) == 1)

// Memory management kind

#if !defined(USING_GC)
#  if defined(__OBJC_GC__)
#     define USING_GC 1
#  else
#    define USING_GC 0
#  endif
#elif EMPTY_DEFINE(USING_GC) 
#   undef USING_GC
#   define USING_GC 1
#endif

#if !defined(USING_ARC)
#  if __has_feature(objc_arc)
#     define USING_ARC 1
#  else
#    define USING_ARC 0
#  endif
#elif EMPTY_DEFINE(USING_ARC)
#   undef USING_ARC
#   define USING_ARC 1
#endif

#if !defined(USING_MRC)
#  if USING_ARC || USING_GC
#     define USING_MRC 0
#  else
#    define USING_MRC 1
#  endif
#elif EMPTY_DEFINE(USING_MRC)
#   undef USING_MRC
#   define USING_MRC 1
#endif

// Remove utility

#undef PREFIX_ONE
#undef EMPTY_DEFINE

// Sanity checks

#if USING_GC
#   if USING_ARC || USING_MRC
#      error "Cannot specify GC and RC memory management"
#   endif
#elif USING_ARC
#   if USING_MRC
#      error "Cannot specify ARC and MRC memory management"
#   endif
#elif !USING_MRC
#   error "Must specify GC, ARC or MRC memory management"
#endif

#if USING_ARC
#   if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_6
#      error "ARC requires at least 10.6"
#   endif
#endif

将其放在项目 .pch 中包含的合适 .h 中

您现在可以#if USING_x 在任何地方控制条件编译。

您还可以排除某些文件在某些​​内存模型下编译的可能性,例如在文件顶部添加:

#if USING_GC | USING_ARC
   #error "Sorry, this file only works with MRC"
#endif

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    相关资源
    最近更新 更多