Skip to content

Instantly share code, notes, and snippets.

@mikeash
Created October 5, 2011 13:28
Show Gist options
  • Save mikeash/1264419 to your computer and use it in GitHub Desktop.
Save mikeash/1264419 to your computer and use it in GitHub Desktop.
Ideas for with blocks for weak variables
// function
void with(id obj, void (^block)(id obj))
{
block(obj);
}
// example use
with(blah, ^(Blah *blah) {
// use blah here
});
// macro
#define with(var, ...) do { __typeof__(var) __tmp_ ## var = var; __typeof(__tmp_ ## var) var = __tmp_ ## var; __VA_ARGS__ } while(0)
// example use
with(blah, {
// use blah here, it's strong
});
// multi-variable macro
#define with(...) do { \
id __with_vars[] = { __VA_ARGS__ }; \
void (^__with_block)(void) = __with_vars[sizeof(__with_vars)/sizeof(*__with_vars) - 1]; \
__with_block(); \
for(unsigned __with_i = 0; __with_i < sizeof(__with_vars)/sizeof(*__with_vars); i++) \
[__with_vars[__with_i] self]; \
} while(0)
// example use
with(foo, bar, baz, ^{
// use foo, bar, baz
});
// utterly awful multi-variable macro
#define IDARRAY(...) ((id[]){ __VA_ARGS__ })
#define IDCOUNT(...) (sizeof(IDARRAY(__VA_ARGS__)) / sizeof(id))
#define with(...) _with_helper(IDARRAY(__VA_ARGS__), IDCOUNT(__VA_ARGS__))
void _with_helper(id objs[], unsigned count)
{
// this is really bad
for(unsigned i = 0; i < count; i++)
objc_autorelease(objc_retain(objs[i]));
}
// example use
with(foo, bar, baz);
// now use foo, bar, baz; if non-nil, will stay non-nil until next autorelease pool pop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment