Skip to content

Instantly share code, notes, and snippets.

@mkhl
Created December 8, 2008 18:27
Show Gist options
  • Save mkhl/33550 to your computer and use it in GitHub Desktop.
Save mkhl/33550 to your computer and use it in GitHub Desktop.
Objective-C macros
// GCC Attribute for autoscoped Obj-C objects
// Source: http://www.cocoabuilder.com/archive/message/cocoa/2009/3/13/232287
#define autoscoped __attribute__((cleanup(releaseObject)))
static inline void releaseObject(id *object)
{
[*object release];
}
- (void) demo
{
autoscoped NSArray *anArray = [[NSArray alloc] init];
// do something with anArray
}
// A quick check if an object is empty
// Source: http://www.wilshipley.com/blog/2005/10/pimp-my-code-interlude-free-code.html
static inline BOOL isEmpty(id thing) {
return (thing == nil)
|| ([thing respondsToSelector:@selector(length)]
&& [(NSData *)thing length] == 0)
|| ([thing respondsToSelector:@selector(count)]
&& [(NSArray *)thing count] == 0);
}
// Helpful macros for object creation
// Source: http://cbarrett.tumblr.com/post/53371495/some-helpful-macros-for-object-creation
#define NSARRAY(...) [NSArray arrayWithObjects: __VA_ARGS__, nil]
#define NSDICT(...) [NSDictionary dictionaryWithObjectsAndKeys: __VA_ARGS__, nil]
#define NSSET(...) [NSSet setWithObjects: __VA_ARGS__, nil]
#define NSBOOL(_X_) ((_X_) ? (id)kCFBooleanTrue : (id)kCFBooleanFalse)
// Use Unions (instead of type-punning) to recast Structs.
// Source: http://cocoawithlove.com/2008/04/using-pointers-to-recast-in-c-is-bad.html
#define UNION_CAST(x, destType) (((union {__typeof__(x) a; destType b;})x).b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment