ReflectableEnum 0.1.2

ReflectableEnum 0.1.2

测试测试
语言语言 Obj-CObjective C
许可 MIT
发行最后发行2016年6月

Arkadiusz Holko 维护。



这是一个宏和一些函数,用于为 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)

缺点

  • REFStringForMemberREFStringForMemberIn\(enumName) 不适用于包含重复值的枚举,例如具有自引用成员的枚举 AccountTypeModerator = AccountTypeAdmin
  • 不能用于在框架和库中已定义的枚举

要求

  • iOS 7 及以上版本
  • OS X 10.9 及以上版本

安装

然后使用以下命令导入: #import <ReflectableEnum/ReflectableEnum.h>

作者

Arkadiusz Holko