• Stars
    star
    153
  • Rank 243,368 (Top 5 %)
  • Language
    Objective-C
  • Created almost 12 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

macros that automate vending an NSString given an enum value (f.x. MyEnumToString(value))

JREnum

Original idea and implementation by Benedict Cohen.

JREnum is a macro that automates creation of functions that blast enums from boring primitive compile-time-land to the fun-filled party environment of runtime.

Let's use a concrete example. Instead of writing:

typedef enum {
    Stream_Disconnected,
    Stream_Connecting,
    Stream_Connected,
    Stream_Disconnecting
}   StreamState;

write:

JREnum(StreamState,
       Stream_Disconnected,
       Stream_Connecting,
       Stream_Connected,
       Stream_Disconnecting);

This will generate the previous typedef enum and will also generate a corresponding suite of functions:

NSString* StreamStateToString(int value)

Given a value, will return the enum's string representation. For example StreamStateToString(2) would return @"Stream_Connected".

When confronted with values not defined in the enumeration, this function will return a placeholder string explaining the situation. For example StreamStateToString(2000) would return @"<unknown StreamState: 2000>".

BOOL StreamStateFromString(NSString *enumLabel, StreamState *enumValue)

Attempts to return the enum's int value given its label. For example StreamStateFromString(@"Stream_Disconnecting", &value) would return YES and set value to 3.

This function returns NO if the label for the enum type is unknown. For example StreamStateFromString(@"lackadaisical", &value) would return NO and leave value untouched.

NSDictionary* StreamStateByValue()

Returns a dictionary whose keys are the enum's values. Used by StreamStateToString().

When enums have multiple overlapping values, the current implementation exhibits last-write-wins behavior.

NSDictionary* StreamStateByLabel()

Returns a dictionary whose keys are the enum's labels. Used by StreamStateFromString(). This is the function you want if you wish to enumerate an enum's labels and values at runtime.

Split Header / Source Files

JREnum() is fine for when you have an enum that lives solely in an .m file. But if you're exposing an enum in a header file, you'll have to use the alternate macros. In your .h, use JREnumDeclare():

JREnumDeclare(StreamState,
              Stream_Disconnected,
              Stream_Connecting,
              Stream_Connected,
              Stream_Disconnecting);

And then use JREnumDefine() in your .m:

JREnumDefine(StreamState);

Explicit Values

You can also explicitly define enum integer values:

JREnum(StreamState,
       Stream_Disconnected = 42,
       Stream_Connecting,
       Stream_Connected,
       Stream_Disconnecting);

In the above scenario, Stream_Disconnected's value will be 42, Stream_Connecting's will be 43 and so on.

You can also use hex values:

JREnum(StreamState,
       Stream_Disconnected = 0x2A,
       Stream_Connecting,
       Stream_Connected,
       Stream_Disconnecting);

That's semantically identical to the above.

New in v1.1 you can use very simple bit-shift masks:

JREnum(Align,
	   AlignLeft         = 1 << 0,
	   AlignRight        = 1 << 1,
	   AlignTop          = 1 << 2,
	   AlignBottom       = 1 << 3,
	   AlignTopLeft      = 0x05,
	   AlignBottomLeft   = 0x09,
	   AlignTopRight     = 0x06,
	   AlignBottomRight  = 0x0A,
	   );

This helps where you want one variable to house a combination of flags:

Align botRight 		  = AlignBottomRight;
Align botRightBitWise = AlignBottom | AlignRight;

NSLog(@"Are They The Same: %@", (botRightBitWise == botRight) ? @"YES" : @"NO");
//=> Are They The Same: YES

But better, because you can go to-and-fro string values:

NSLog(@"How is that combo aligned? %@", AlignToString(botRightBitWise));
//=> How is that combo aligned? AlignBottomRight

TODO

Version History

v1.2: Jul 4 2017

v1.1: Mar 25 2014

  • [NEW] Add support for hex constants. (Alex Gray)
  • [NEW] Add support for very simple bit-shifting constants. (rentzsch)

v1.0.1: May 28 2013

v1.0: Apr 09 2013

  • Minor bug fix from 0.2.

v0.2: Dec 10 2012

  • [NEW] Generalized to support bidirectional enum label/value lookup and full runtime access to lookup dictionary.
  • [NEW] Add passing tests.
  • [NEW] Write this README.

v0.1: Dec 9 2012

  • [NEW] Devised way to allow split declaration/definition macros to allow use in header/source files.

Prelude: Dec 8 2012

More Repositories

1

mogenerator

Core Data code generation
Objective-C
3,029
star
2

jrswizzle

one-stop-shop for all your method swizzling needs
Objective-C
2,659
star
3

mach_inject

interprocess code injection for Mac OS X
C
810
star
4

clicktoflash

WebKit plug-in to prevent automatic loading of Adobe Flash content
Objective-C
714
star
5

markdownlive

Purpose-built Markdown Editor for Mac OS X with Live Preview
C
496
star
6

mach_override

runtime function overriding for Mac OS X
C
427
star
7

AutoLayoutShorthand

alternative system for creating and adding Cocoa Auto Layout constraints
Objective-C
355
star
8

mach_star

code injection and function overriding for Mac OS X
C
254
star
9

jrfeedbackprovider

nonviral cocoa source for implementing an application feedback panel (for bugs, feature requests and support)
Objective-C
114
star
10

lich

Simple, general, human-sympathetic binary data format
Objective-C
104
star
11

OAuthConsumer

fork of http://code.google.com/p/oauth/ 's Obj-C 2 API
Objective-C
82
star
12

JRTranscriptView

Purpose-built text view for logging output. iOS 7+
Objective-C
67
star
13

stressdrive

tool to completely fill a drive with random data and ensure it can be entirely correctly read back
C
60
star
14

NSInvocation-blocks

Even-easier NSInvocation creation thanks to blocks
Objective-C
54
star
15

JRErr

light at the end of the NSError** tunnel
Objective-C
51
star
16

SafariSessionSaver

Simple app that archives (and restores) Safari's currently-open windows+tabs
Objective-C
50
star
17

MagicHat

Objective-C Binary Documentation Tool. Think classdump with a hyperlinked GUI.
C
43
star
18

bdalias

Simple Cocoa wrapper for Carbon Aliases
Objective-C
38
star
19

Blitz

20 slides. 15 seconds each. 5 minutes total. Go.
Objective-C
32
star
20

JRTruthTable

tell it the current conditions, and it will tell you the current state
Objective-C
31
star
21

node-mysql-oil

slick api on top of node-mysql
JavaScript
30
star
22

clonedrive

paranoid bytewise drive cloning
C
26
star
23

JRLog

Simple but flexible Log4J-like logging system for Objective-C
Objective-C
26
star
24

SafeToUnplug

tiny faceless background app that notfies you when it's actually safe to unplug a drive
Objective-C
22
star
25

ForceQuitUnresponsiveApps

Small background app for Mac OS X 10.6+ that automatically force-quits hung apps
C
22
star
26

BlockStep

makes async code (Obj-C+Blocks) read kinda like sync code
Objective-C
21
star
27

NSKeyedArchiver-butWithNSError

Categories to make NSKeyedArchiver & NSKeyedUnarchiver easier to use and report errors via NSError**
Objective-C
19
star
28

CodaAutosaveOnDeactivate

Coda plugin to automatically save edited documents upon application focus resignation
C
19
star
29

nginx-homebrew-support

support files for nginx-homebrew running as a machine-wide service
Ruby
15
star
30

OpenRadarApp

client-side app for automatically posting Apple-filed RADARs to OpenRadar
JavaScript
14
star
31

webedit

think TextEdit but using WebKit
Objective-C
13
star
32

hypo

why just #import a header file when you can import the object itself?
Objective-C
12
star
33

JRKVOBlocks

Another take on integrating KVO with Blocks. 10.6+manual memory management assumed
Objective-C
12
star
34

ComplimentKit

opt-in to automatically receive flattrs (microdonations) as your users use your mac app
12
star
35

UIView-jr_addConstraints

easier notation for adding Auto Layout constraints to UIView
Objective-C
11
star
36

CoreData-JRExtensions

Objective-C
10
star
37

JRPDFLabel

Design your interface in Interface Builder using custom fonts without having to bundle them
Objective-C
9
star
38

NSXReturnThrowError

Adds origin information to NSError and eases wrapping error codes
Objective-C
9
star
39

Transformation-Matrix-Funhouse

demo of -webkit-transform: matrix3d() (and transformation matrices in general)
JavaScript
9
star
40

JSRegexTeststand

simple single-page app to dynamically develop and test javascript regular expressions
HTML
9
star
41

jryaml

Modern YAML for ObjC. Uses libyaml and Mike Schrag's MDYAML
8
star
42

woplat

WOInstaller + Wonder Web Server Adaptor + OS Support Files
C
8
star
43

unpopular

Chrome Extension that hides indicators of social status on GitHub (watchers, stars, forks) and Twitter (followers, retweets, favs)
CSS
8
star
44

UIView-jr_viewInSuperview

Let's make it easier to create an Auto Layout-ed UIView
Objective-C
7
star
45

MiscMerge

textual templates for Obj-C
Objective-C
6
star
46

BillingsCal

Simple comprehensive live reporting of Billings' database
Objective-C
6
star
47

TwitterReflectorDish

a simple twitter reflector dish (used for @c4)
6
star
48

Function.introspect.js

Small javascript library that interrogates a function to return its name, argument names and source code
JavaScript
6
star
49

ply

minimalist CSS library
5
star
50

xib2pdflabels

tool that generates a multipage PDF, one page per JRPDFLabel view
Objective-C
5
star
51

atomicity

Blast from the Classic Mac OS past. Atomic Locks, Stacks, Guarded Stacks, Queues, and Guarded Queues
C
5
star
52

JRCenteringScrollView

UIScrollView subclass that uses Auto Layout to center its content
Objective-C
5
star
53

slowgold

minimal osx app launcher/switcher
Objective-C
4
star
54

docker-webobjects

WebObjects under Docker. Dead can dance.
4
star
55

catchr

es6 const assignment even with exceptional code
JavaScript
4
star
56

git-import-commit

like git-cherry-pick, but with more sledgehammer
C
4
star
57

CALayer-jr_UIColor

Easily get+set CALayer background and border colors as UIColors in an ARC-safe fashion.
Objective-C
4
star
58

pomodoro

fork of http://github.com/ugol/pomodoro
C
4
star
59

rentzsch.tumblr.com-theme

Tumblr theme used by rentzsch.tumblr.com + MarsEdit
3
star
60

nsxmlelement-elementwithxmlformat

Easier ObjC XML generation
Objective-C
3
star
61

burndeck

SIMBL plugin that adds CD burning to http://www.tapedeckapp.com
Objective-C
3
star
62

simplest-multiplexed-framing-protocol

simple binary protocol for concurrent async unix sockets
C
3
star
63

jsongo

like mongo db, except stores data in git-friendly flat json files
TypeScript
3
star
64

JRLogDemo

Simple app demonstrating JRLog
Objective-C
3
star
65

docker-webobjects-wotaskd

WebObjects' wotaskd in handy container form
3
star
66

qunit

would be a fork of http://github.com/jquery/qunit if that actually held anything
JavaScript
3
star
67

access-date

AppleScript Addition (osax) to retrieve a file's last access date
C
2
star
68

Saw

External-process output destination for JRLog
Objective-C
2
star
69

CoreEndian-RuntimeTarget

Header file with macros for targeting specific endian targets with CoreEndian
C
2
star
70

ReactiveCocoaExample1

Objective-C
2
star
71

dbslayer

unofficial github clone of official dbslayer svn repo
JavaScript
2
star
72

node-arq

node.js implementation of arq backup
2
star
73

jsontable

Simple, efficient, flexible, streamable tabular textual data format
TypeScript
2
star
74

mach_error-Decoder-Ring

simple+lame cocoa app that decodes mach_error integers
Objective-C
2
star
75

Math.uuid.js

fork of Robert Kieffer's Math.uuid.js in jquery.pkg format
JavaScript
2
star
76

elemental

An intrusive, fast (constant-speed), doubly-linked list in C
C
2
star
77

usc

United States Customary Unit lengths (inches, feet) calculator in JS
TypeScript
1
star
78

wiki

wolf's personal wiki
1
star
79

do-dns

command-line tool for downloading and uploading Digital Ocean DNS records
TypeScript
1
star
80

SwiftCoreDataRelationshipRepro

simple Mac app that reproduces failure to set a to-one relationship using Core Data with Swift (Xcode 6b3-4)
Swift
1
star
81

docker-apache-webobjects

Apache + WebObjects Adapter under Docker
1
star
82

giles

simple ajax frontend to DBSlayer
1
star
83

node-google-image-search-url-results

simple node frontend to google image search results (as an array of urls)
JavaScript
1
star
84

WhitelistDeliciousContentSecurityPolicy

Adds https://delicious.com to GitHub's Content-Security-Policy Header so its bookmarklet works
JavaScript
1
star
85

pretty164

Simple E.164 dash-inserter
TypeScript
1
star