常用的Objective-C特性检查

来源:互联网 发布:免备案免费php空间 编辑:程序博客网 时间:2024/05/18 02:40
  • 检查是否支持blocks
 __has_extension(blocks)
  • 检查是否支持instancetye上下文关键词
__has_feature(objc_instancetype)
@interface A+ (instancetype)constructAnA;@end
  • 检查是否支持arc
__has_feature(objc_arc)
__has_feature(objc_arc_weak) //同时检查是否支持__weak指针
  • 检查是否支持固定基础类型的枚举
__has_feature(objc_fixed_enum)
typedef enum : unsigned char { Red, Green, Blue } Color;
  • 检查是否支持对象字面值
__has_feature(objc_array_literals)
__has_feature(objc_dictionary_literals)
NSArray *array = @[ @"Hello", NSApp, [NSNumber numberWithInt:42] ];
NSDictionary *dictionary = @{    @"name" : NSUserName(),    @"date" : [NSDate date],    @"processInfo" : [NSProcessInfo processInfo]};
  • 检查是否支持对象下标(OC的对象指针现在可以像C一样做下标操作)
__has_feature(objc_subscripting)
NSMutableArray *array = ...;NSUInteger idx = ...;id newObject = ...;id oldObject = array[idx];array[idx] = newObject;         // replace oldObject with newObjectNSMutableDictionary *dictionary = ...;NSString *key = ...;oldObject = dictionary[key];dictionary[key] = newObject;    // replace oldObject with newObject
  • 检查是否支持属性的自动合成(不使用@dynamic的情况下,自动生成存取方法)
__has_feature(objc_default_synthesize_properties)


使用范例(来源:MBProgressHUD源码):
#ifndef MB_INSTANCETYPE#if __has_feature(objc_instancetype)#define MB_INSTANCETYPE instancetype#else#define MB_INSTANCETYPE id#endif#endif#ifndef MB_STRONG#if __has_feature(objc_arc)#define MB_STRONG strong#else#define MB_STRONG retain#endif#endif#ifndef MB_WEAK#if __has_feature(objc_arc_weak)#define MB_WEAK weak#elif __has_feature(objc_arc)#define MB_WEAK unsafe_unretained#else#define MB_WEAK assign#endif#endif#if NS_BLOCKS_AVAILABLEtypedef void (^MBProgressHUDCompletionBlock)();#endif