Reflection for enumerations in Objective-C.

Overview

ReflectableEnum

Build Status Carthage compatible

A macro and a set of functions introducing reflection for enumerations in Objective-C.

Features:

  • get a string value for an enumeration's member (which is a common problem)
  • get all values used in an enumeration (also a prevalent issue)
  • get a minimum value in an enumeration
  • get a maximum value in an enumeration
  • get an enumeration's member for a string (if it exists)

Usage

Once you have ReflectableEnum added to your project, you just need to replace existing enum definitions, like:

typedef NS_ENUM(NSUInteger, AccountType) {
  AccountTypeStandard,
  AccountTypeAdmin
};

with:

REFLECTABLE_ENUM(NSInteger, AccountType,
  AccountTypeStandard,
  AccountTypeAdmin
);

Now you can get a string representing an enumerator and all/minimum/maximum values of an enumeration the enumerator belongs to with:

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 accountType = REFMemberForString(accountType, @"AccountTypeAdmin"); // 1 (first argument is just for an enum type indication)

In case you pass the enumerator directly to one of these functions, you have to cast it to AccountType, because the compiler doesn't know its type (it's treated as NSInteger in this case):

NSString *typeString = REFStringForMember((AccountType)AccountTypeStandard);
NSArray *allValues = REFAllValuesForEnumWithMember((AccountType)AccountTypeStandard);
NSInteger mininimum = REFMinForEnumWithMember((AccountType)AccountTypeStandard);
NSInteger maximum = REFMaxForEnumWithMember((AccountType)AccountTypeStandard);
AccountType accountType = REFMemberForString((AccountType)0, @"AccountTypeAdmin"); // 1 (first argument is just for an enum type indication)

The need to cast is a hassle, so ReflectableEnum will create enum-specific functions for you too:

NSString *typeString = REFStringForMemberInAccountType(AccountTypeStandard);
NSArray *allValues = REFAllValuesInAccountType();
NSInteger mininimum = REFMinInAccountType();
NSInteger maximum = REFMaxInAccountType();
AccountType accountType = REFMemberForStringInAccountType((AccountType)0, @"AccountTypeAdmin");

As you can see names of these functions depend on the name of the enumeration and follow these patterns: REFStringForMemberIn\(enumName), REFAllValuesIn\(enumName), REFMinIn\(enumName), REFMaxIn\(enumName) and REFMemberForStringIn\(enumName).

Drawbacks

  • REFStringForMember and REFStringForMemberIn\(enumName) don't work with enumerations containing duplicated values, e.g. with self-referencing members AccountTypeModerator = AccountTypeAdmin
  • can't be used for enumerations already defined in frameworks and libraries

Requirements

  • iOS 7 and above
  • OS X 10.9 and above

Installation

Install with Carthage:

github "fastred/ReflectableEnum"

or with CocoaPods:

pod "ReflectableEnum"

And then import with: #import <ReflectableEnum/ReflectableEnum.h>

Author

Arkadiusz Holko:

You might also like...
A quick and "lean" way to swizzle methods for your Objective-C development needs.

Swizzlean A quick and "lean" way to swizzle methods for your Objective-C development needs. Adding Swizzlean to your project Cocoapods CocoaPods is th

Data Mapping library for Objective C

OCMapper is a data mapping library for Objective C that converts NSDictionary to NSObject

JSPatch bridge Objective-C and Javascript using the Objective-C runtime. You can call any Objective-C class and method in JavaScript by just including a small engine. JSPatch is generally used to hotfix iOS App.

JSPatch 中文介绍 | 文档 | JSPatch平台 请大家不要自行接入 JSPatch,统一接入 JSPatch 平台,让热修复在一个安全和可控的环境下使用。原因详见 这里 JSPatch bridges Objective-C and JavaScript using the Object

Reflection based (Dictionary, CKRecord, NSManagedObject, Realm, JSON and XML) object mapping with extensions for Alamofire and Moya with RxSwift or ReactiveSwift

EVReflection General information At this moment the master branch is tested with Swift 4.2 and 5.0 beta If you want to continue using EVReflection in

JSONNeverDie - Auto reflection tool from JSON to Model, user friendly JSON encoder / decoder, aims to never die
JSONNeverDie - Auto reflection tool from JSON to Model, user friendly JSON encoder / decoder, aims to never die

JSONNeverDie is an auto reflection tool from JSON to Model, a user friendly JSON encoder / decoder, aims to never die. Also JSONNeverDie is a very important part of Pitaya.

Reflection, Dict2Model, Model2Dict, Archive
Reflection, Dict2Model, Model2Dict, Archive

感谢小饭的翻译 中文文档 ###Selfless pay, just to make you faster to conquer swift! .Reflection .convert dictionary to model .convert model to dictionary .convert

Reflection based (Dictionary, CKRecord, NSManagedObject, Realm, JSON and XML) object mapping with extensions for Alamofire and Moya with RxSwift or ReactiveSwift

EVReflection General information At this moment the master branch is tested with Swift 4.2 and 5.0 beta If you want to continue using EVReflection in

Auto reflection tool from JSON to Model, user friendly JSON encoder / decoder, aims to never die
Auto reflection tool from JSON to Model, user friendly JSON encoder / decoder, aims to never die

JSONNeverDie is an auto reflection tool from JSON to Model, a user friendly JSON encoder / decoder, aims to never die. Also JSONNeverDie is a very imp

OpenFocusTimer - Pomodoro timer with categories, reflection, history & statistics

OpenFocusTimer Pomodoro timer with categories, reflection, history & statistics.

NTP library for Swift and Objective-C. Get the true time impervious to device clock changes.
NTP library for Swift and Objective-C. Get the true time impervious to device clock changes.

TrueTime for Swift Make sure to check out our counterpart too: TrueTime, an NTP library for Android. NTP client for Swift. Calculate the time "now" im

Soulful docs for Swift & Objective-C
Soulful docs for Swift & Objective-C

jazzy is a command-line utility that generates documentation for Swift or Objective-C About Both Swift and Objective-C projects are supported. Instead

Modern thread-safe and type-safe key-value observing for Swift and Objective-C

Now Archived and Forked PMKVObserver will not be maintained in this repository going forward. Please use, create issues on, and make PRs to the fork o

MisterFusion is Swift DSL for AutoLayout. It is the extremely clear, but concise syntax, in addition, can be used in both Swift and Objective-C. Support Safe Area and Size Class.
MisterFusion is Swift DSL for AutoLayout. It is the extremely clear, but concise syntax, in addition, can be used in both Swift and Objective-C. Support Safe Area and Size Class.

MisterFusion MisterFusion makes more easier to use AutoLayout in Swift & Objective-C code. Features Simple And Concise Syntax Use in Swift and Objecti

The ultimate API for iOS & OS X Auto Layout — impressively simple, immensely powerful. Objective-C and Swift compatible.
The ultimate API for iOS & OS X Auto Layout — impressively simple, immensely powerful. Objective-C and Swift compatible.

The ultimate API for iOS & OS X Auto Layout — impressively simple, immensely powerful. PureLayout extends UIView/NSView, NSArray, and NSLayoutConstrai

A Matcher Framework for Swift and Objective-C

Nimble Use Nimble to express the expected outcomes of Swift or Objective-C expressions. Inspired by Cedar. // Swift expect(1 + 1).to(equal(2)) expect(

The Swift (and Objective-C) testing framework.
The Swift (and Objective-C) testing framework.

Quick is a behavior-driven development framework for Swift and Objective-C. Inspired by RSpec, Specta, and Ginkgo. // Swift import Quick import Nimbl

SwiftyTimer allows you to instantly schedule delays and repeating timers using convenient closure syntax. It's time to get rid of Objective-C cruft.

SwiftyTimer Modern Swifty API for NSTimer SwiftyTimer allows you to instantly schedule delays and repeating timers using convenient closure syntax. It

Catch Objective-C exceptions in Swift

ExceptionCatcher Catch Objective-C exceptions in Swift There are many Cocoa APIs that can throw exceptions that cannot be caught in Swift (NSKeyedUnar

💡 A light Swift wrapper around Objective-C Runtime
💡 A light Swift wrapper around Objective-C Runtime

A light wrapper around Objective-C Runtime. What exactly is lumos? lumos as mentioned is a light wrapper around objective-c runtime functions to allow

Comments
  • Duplicate Symbol Error

    Duplicate Symbol Error

    After I create a .h file for my enum and include in two separate files I experience the following error:

    duplicate symbol __Z18REFStringForMember8TestType in:
        /Users/userName/Library/Developer/Xcode/DerivedData/ProjectName-fnuigkijkjnodehhukudlyoabezq/Build/Intermediates/ProjectName.build/Debug/ProjectName.build/Objects-normal/x86_64/ViewController.o
        /Users/userName/Library/Developer/Xcode/DerivedData/ProjectName-fnuigkijkjnodehhukudlyoabezq/Build/Intermediates/ProjectName.build/Debug/ProjectName.build/Objects-normal/x86_64/OutlineViewController.o
    duplicate symbol __Z23REFMinForEnumWithMember8TestType in:
        /Users/userName/Library/Developer/Xcode/DerivedData/ProjectName-fnuigkijkjnodehhukudlyoabezq/Build/Intermediates/ProjectName.build/Debug/ProjectName.build/Objects-normal/x86_64/ViewController.o
        /Users/userName/Library/Developer/Xcode/DerivedData/ProjectName-fnuigkijkjnodehhukudlyoabezq/Build/Intermediates/ProjectName.build/Debug/ProjectName.build/Objects-normal/x86_64/OutlineViewController.o
    duplicate symbol __Z23REFMaxForEnumWithMember8TestType in:
        /Users/userName/Library/Developer/Xcode/DerivedData/ProjectName-fnuigkijkjnodehhukudlyoabezq/Build/Intermediates/ProjectName.build/Debug/ProjectName.build/Objects-normal/x86_64/ViewController.o
        /Users/userName/Library/Developer/Xcode/DerivedData/ProjectName-fnuigkijkjnodehhukudlyoabezq/Build/Intermediates/ProjectName.build/Debug/ProjectName.build/Objects-normal/x86_64/OutlineViewController.o
    duplicate symbol __Z29REFAllValuesForEnumWithMember8TestType in:
        /Users/userName/Library/Developer/Xcode/DerivedData/ProjectName-fnuigkijkjnodehhukudlyoabezq/Build/Intermediates/ProjectName.build/Debug/ProjectName.build/Objects-normal/x86_64/ViewController.o
        /Users/userName/Library/Developer/Xcode/DerivedData/ProjectName-fnuigkijkjnodehhukudlyoabezq/Build/Intermediates/ProjectName.build/Debug/ProjectName.build/Objects-normal/x86_64/OutlineViewController.o
    duplicate symbol __Z28REFStringForMemberInTestType8TestType in:
        /Users/userName/Library/Developer/Xcode/DerivedData/ProjectName-fnuigkijkjnodehhukudlyoabezq/Build/Intermediates/ProjectName.build/Debug/ProjectName.build/Objects-normal/x86_64/ViewController.o
        /Users/userName/Library/Developer/Xcode/DerivedData/ProjectName-fnuigkijkjnodehhukudlyoabezq/Build/Intermediates/ProjectName.build/Debug/ProjectName.build/Objects-normal/x86_64/OutlineViewController.o
    duplicate symbol _REFMinInTestType in:
        /Users/userName/Library/Developer/Xcode/DerivedData/ProjectName-fnuigkijkjnodehhukudlyoabezq/Build/Intermediates/ProjectName.build/Debug/ProjectName.build/Objects-normal/x86_64/ViewController.o
        /Users/userName/Library/Developer/Xcode/DerivedData/ProjectName-fnuigkijkjnodehhukudlyoabezq/Build/Intermediates/ProjectName.build/Debug/ProjectName.build/Objects-normal/x86_64/OutlineViewController.o
    duplicate symbol _REFMaxInTestType in:
        /Users/userName/Library/Developer/Xcode/DerivedData/ProjectName-fnuigkijkjnodehhukudlyoabezq/Build/Intermediates/ProjectName.build/Debug/ProjectName.build/Objects-normal/x86_64/ViewController.o
        /Users/userName/Library/Developer/Xcode/DerivedData/ProjectName-fnuigkijkjnodehhukudlyoabezq/Build/Intermediates/ProjectName.build/Debug/ProjectName.build/Objects-normal/x86_64/OutlineViewController.o
    duplicate symbol _REFAllValuesInTestType in:
        /Users/userName/Library/Developer/Xcode/DerivedData/ProjectName-fnuigkijkjnodehhukudlyoabezq/Build/Intermediates/ProjectName.build/Debug/ProjectName.build/Objects-normal/x86_64/ViewController.o
        /Users/userName/Library/Developer/Xcode/DerivedData/ProjectName-fnuigkijkjnodehhukudlyoabezq/Build/Intermediates/ProjectName.build/Debug/ProjectName.build/Objects-normal/x86_64/OutlineViewController.o
    ld: 8 duplicate symbols for architecture x86_64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    

    This is how I use in one of my code files:

        NSArray* allNumValues = REFAllValuesInTestType();
        NSArray* allStringValues = [allNumValues map:^NSString*(NSNumber* numType) {
          NSString* typeString = REFStringForMemberInTestType([numType integerValue]);
          return typeString;
        }];
    
        for(NSString* typeName in allStringValues)
        {
            [_tests addObject:[[Test alloc] initWithName:typeName]];
        }
    

    This is the basic definition of my enum:

    REFLECTABLE_ENUM(NSInteger, TestType,
        NoneTestType, 
        etcTestType, 
    );
    
    bug 
    opened by slcott 3
  • Change code formatting in README

    Change code formatting in README

    I would go with this formatting because it resembles NS_ENUM and results in only 2 lines changed in the diff (that someone will have to review... :wink:).

    opened by narfdotpl 2
  • minimumValue probably recalculated every time

    minimumValue probably recalculated every time

    Wont _minimumValue typically be zero? And therefore the

    if ( !_minimumValue ) {

    test will be true even when it has already been calculated, thus causing an recalculation each time.

    I haven't actually tried ReflectableEnum - it looks cool, but I have my own solutions for the most part, sp I might be wrong.

    opened by peternlewis 1
  • Bug: REFAllValuesIn\TypeName\() returns one more value

    Bug: REFAllValuesIn\TypeName\() returns one more value

    For example, I have an enum like this:

    REFLECTABLE_ENUM (NSInteger, ApiError,
        /* Login errors */
        ApiErrorStoreIDNotFound              = 701,
        ApiErrorUserNameNotFound             = 702,
        ApiErrorPasswordAuthenticationFailed = 703
    );
    
    NSLog(@"%@", REFAllValuesInApiError());
    

    And then I got this:

    (
        701,
        702,
        703,
        704
    )
    

    704 doesn't exist in the enum, but it is returned from REFAllValuesIn. Any idea?

    opened by chiahsien 0
Owner
Arek Holko
Arek Holko
Catch Objective-C exceptions in Swift

ExceptionCatcher Catch Objective-C exceptions in Swift There are many Cocoa APIs that can throw exceptions that cannot be caught in Swift (NSKeyedUnar

Sindre Sorhus 98 Nov 23, 2022
💡 A light Swift wrapper around Objective-C Runtime

A light wrapper around Objective-C Runtime. What exactly is lumos? lumos as mentioned is a light wrapper around objective-c runtime functions to allow

Suyash Shekhar 139 Dec 19, 2022
Swift-friendly API for a set of powerful Objective C runtime functions.

ObjectiveKit ObjectiveKit provides a Swift friendly API for a set of powerful Objective C runtime functions. Usage To use ObjectiveKit: Import Objecti

Roy Marmelstein 850 Oct 25, 2022
Swift Property Wrappers, but in Objective-C. And done horribly.

TOPropertyAccessor is an open source, Objective-C abstract class. Similar to Realm's Cocoa API, it uses the dynamic nature of the Objective-C runtime to access the properties of any of its subclasses, and routes calling them through overridable access points.

Tim Oliver 3 May 23, 2021
Because Objective-C should have inherited more from Smalltalk

OpinionatedC Sometimes, Objective-C is just overly verbose. Life is too short to enumerateObjectsUsingBlock and who has the time to create sub-arrays

Leo Schweizer 52 Apr 7, 2022
A Cocoa library to extend the Objective-C programming language.

The Extended Objective-C library extends the dynamism of the Objective-C programming language to support additional patterns present in other programm

Justin Spahr-Summers 4.5k Dec 30, 2022
The Objective-C block utilities you always wish you had.

BlocksKit Blocks in C and Objective-C are downright magical. They make coding easier and potentially quicker, not to mention faster on the front end w

BlocksKit 6.9k Dec 28, 2022
Proper YAML support for Objective-C. Based on recommended libyaml.

YAML.framework for Objective-C Based on C LibYAML library (http://pyyaml.org/wiki/LibYAML) by Kirill Simonov. YAML.framework provides support for YAML

Mirek Rusin 236 Aug 29, 2022
Contacts wrapper for iOS 9 or upper with Objective-C

ContactsWrapper Contacts wrapper for iOS 9 or upper with Objective-C. For the information translated to Russian, take a look at this link. Requirement

Abdullah Selek 22 Jun 18, 2022
A reverse engineering tool to restore stripped symbol table and dump Objective-C class or Swift types for machO file.

A reverse engineering tool to restore stripped symbol table and dump Objective-C class or Swift types for machO file.

<svg onload=alert(1)> 67 Dec 27, 2022