Skip to content

Instantly share code, notes, and snippets.

@orj
Created May 22, 2011 14:05
Show Gist options
  • Save orj/985501 to your computer and use it in GitHub Desktop.
Save orj/985501 to your computer and use it in GitHub Desktop.
A Objective-C macro for generating @synthesize statements. Useful when you want to enforce a specific naming convention on synthesized ivars.
/*!
\def N_ARGS
\brief Macro that can tell how many variable arguments have been passed to it (up to a total of 16).
*/
#define N_ARGS(...) N_ARGS_1(__VA_ARGS__, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define N_ARGS_1(...) N_ARGS_2(__VA_ARGS__)
#define N_ARGS_2(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, n, ...) n
/*!
\def CAT
\brief Concatinate two symbols.
*/
#define CAT(a, b) _PRIMITIVE_CAT(a, b)
#define _PRIMITIVE_CAT(a, b) a##b
/*!
\def PROPERTY_IVAR
\brief Returns gets the ivar name of a property with the specified \a name.
\param name The name of the property.
\return The ivar name.
*/
#define PROPERTY_IVAR(name) CAT(name, _)
/*!
\def SYNTHESIZE
\brief Helper macro for specifying synthesized properties.
*/
#define SYNTHESIZE(...) @synthesize CAT(_SYNTHESIZE_, N_ARGS(__VA_ARGS__))(__VA_ARGS__)
#define _SYNTHESIZE_H(x) x=PROPERTY_IVAR(x)
#define _SYNTHESIZE_1(a) _SYNTHESIZE_H(a)
#define _SYNTHESIZE_2(a, b) _SYNTHESIZE_H(a), _SYNTHESIZE_H(b)
#define _SYNTHESIZE_3(a, ...) _SYNTHESIZE_H(a), _SYNTHESIZE_2(__VA_ARGS__)
#define _SYNTHESIZE_4(a, ...) _SYNTHESIZE_H(a), _SYNTHESIZE_3(__VA_ARGS__)
#define _SYNTHESIZE_5(a, ...) _SYNTHESIZE_H(a), _SYNTHESIZE_4(__VA_ARGS__)
#define _SYNTHESIZE_6(a, ...) _SYNTHESIZE_H(a), _SYNTHESIZE_5(__VA_ARGS__)
#define _SYNTHESIZE_7(a, ...) _SYNTHESIZE_H(a), _SYNTHESIZE_6(__VA_ARGS__)
#define _SYNTHESIZE_8(a, ...) _SYNTHESIZE_H(a), _SYNTHESIZE_7(__VA_ARGS__)
#define _SYNTHESIZE_9(a, ...) _SYNTHESIZE_H(a), _SYNTHESIZE_8(__VA_ARGS__)
#define _SYNTHESIZE_10(a, ...) _SYNTHESIZE_H(a), _SYNTHESIZE_9(__VA_ARGS__)
#define _SYNTHESIZE_11(a, ...) _SYNTHESIZE_H(a), _SYNTHESIZE_10(__VA_ARGS__)
#define _SYNTHESIZE_12(a, ...) _SYNTHESIZE_H(a), _SYNTHESIZE_11(__VA_ARGS__)
#define _SYNTHESIZE_13(a, ...) _SYNTHESIZE_H(a), _SYNTHESIZE_12(__VA_ARGS__)
#define _SYNTHESIZE_14(a, ...) _SYNTHESIZE_H(a), _SYNTHESIZE_13(__VA_ARGS__)
#define _SYNTHESIZE_15(a, ...) _SYNTHESIZE_H(a), _SYNTHESIZE_14(__VA_ARGS__)
#define _SYNTHESIZE_16(a, ...) _SYNTHESIZE_H(a), _SYNTHESIZE_15(__VA_ARGS__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment