这是一个宏和一些函数,用于为 Objective-C 中的枚举引入反射。
特性
将 ReflectableEnum 添加到您的项目后,您只需替换现有的枚举定义,例如:
typedef NS_ENUM(NSUInteger, AccountType) {
AccountTypeStandard,
AccountTypeAdmin
};
改为:
REFLECTABLE_ENUM(NSInteger, AccountType,
AccountTypeStandard,
AccountTypeAdmin
);
现在,您可以使用以下方式获取枚举代表的字符串以及枚举成员所属枚举的所有/最小/最大值:
AccountType accountType = AccountTypeStandard;
NSString *typeString = REFStringForMember(accountType); // @"AccountTypeStandard"
NSArray *allValues = REFAllValuesForEnumWithMember(accountType); // @[@0, @1]
NSInteger mininimum = REFMinForEnumWithMember(accountType); // 0
NSInteger maximum = REFMaxForEnumWithMember(accountType); // 1
如果您将枚举直接传递给这些函数之一,您需要将其转换为 AccountType
,因为编译器不知道其类型(在这种情况下,它被视为 NSInteger
)
NSString *typeString = REFStringForMember((AccountType)AccountTypeStandard);
NSArray *allValues = REFAllValuesForEnumWithMember((AccountType)AccountTypeStandard);
NSInteger mininimum = REFMinForEnumWithMember((AccountType)AccountTypeStandard);
NSInteger maximum = REFMaxForEnumWithMember((AccountType)AccountTypeStandard);
需要转换是件麻烦事儿,因此 ReflectableEnum
还为您创建了针对特定枚举的函数
NSString *typeString = REFStringForMemberInAccountType(AccountTypeStandard);
NSArray *allValues = REFAllValuesInAccountType();
NSInteger mininimum = REFMinInAccountType();
NSInteger maximum = REFMaxInAccountType();
如您所见,这些函数的名称取决于枚举的名称,并遵循以下模式:例如,REFStringForMemberIn\(enumName)
、REFAllValuesIn\(enumName)
、REFMinIn\(enumName)
和 REFMaxIn\(enumName)
REFStringForMember
和 REFStringForMemberIn\(enumName)
不适用于包含重复值的枚举,例如具有自引用成员的枚举 AccountTypeModerator = AccountTypeAdmin
然后使用以下命令导入: #import <ReflectableEnum/ReflectableEnum.h>
Arkadiusz Holko