常用的Objective-C特性检查

本文介绍了如何检查Objective-C项目中是否支持关键特性,包括blocks、instancetype、ARC、固定基础类型枚举、对象字面量、对象下标操作以及属性的自动合成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 检查是否支持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 newObject

NSMutableDictionary *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_AVAILABLE
typedef void (^MBProgressHUDCompletionBlock)();
#endif




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值