Skip to content

Instantly share code, notes, and snippets.

@mbigatti
Last active December 24, 2015 05:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbigatti/6750958 to your computer and use it in GitHub Desktop.
Save mbigatti/6750958 to your computer and use it in GitHub Desktop.
A macro for dynamic properties in categories
//
// Dynamic properties in categories
//
// @see http://www.davidhamrick.com/2012/05/28/Adding-Properties-to-an-Objective-C-Category-Revisted.html
// @see https://twitter.com/nicklockwood/status/384088702768922625
// @see http://www.tuaw.com/2013/04/10/devjuice-better-objective-c-associated-objects/
// @see http://stackoverflow.com/questions/16020918/avoid-extra-static-variables-for-associated-objects-keys
//
// Remember to add #import <objc/runtime.h> in implementation.
//
#define ADD_DYNAMIC_PROPERTY(PROPERTY_TYPE, PROPERTY_NAME, SETTER_NAME) \
@dynamic PROPERTY_NAME; \
- ( PROPERTY_TYPE ) PROPERTY_NAME \
{ \
return ( PROPERTY_TYPE ) objc_getAssociatedObject(self, @selector(PROPERTY_NAME) ); \
} \
\
- (void) SETTER_NAME :( PROPERTY_TYPE ) PROPERTY_NAME \
{ \
objc_setAssociatedObject(self, @selector(PROPERTY_NAME), PROPERTY_NAME, OBJC_ASSOCIATION_RETAIN); \
} \
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment