Skip to content

Instantly share code, notes, and snippets.

@hlung
Last active September 8, 2015 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hlung/9d13e1a8b274121ee489 to your computer and use it in GitHub Desktop.
Save hlung/9d13e1a8b274121ee489 to your computer and use it in GitHub Desktop.
Objective-C In-line block declaration can be hard to remember. Here are example declaration and usage.
// using block in interface property, use "copy"
@property (copy, nonatomic) void (^simpleBlock)(void);
@property (copy, nonatomic) BOOL (^blockWithParamter)(NSString *input);
// block variable declaration
void (^addButton)(SEL, NSString *) = ^(SEL action, NSString *imageName) {
};
// block typedef shorthand
typedef BOOL (^FailureHandler)(NSError *error);
// method that returns a block
+ (BOOL(^)(NSError *error))validationBlock;
+ (FailureHandler)validationBlock;
// using block in method declaration
- (BOOL)connectWithCompletion:(void (^)(BOOL success))block;
// --- Examples ---
// This is a copy-paste job with a few changes, so you could use a define,
// but it is getting a little complex. Instead, try using a block.
// credit: http://stablekernel.com/blog/define-vs-const-vs-the-world/
// set up buttons with each origin.y 60 away from each other
__block CGRect r = CGRectMake(20, 20, 80, 40);
void (^addButton)(SEL, NSString *) = ^(SEL action, NSString *imageName) {
UIButton *b = ...;
...
r.origin.y += 60;
};
addButton(@selector(action1:), @"button1");
addButton(@selector(action2:), @"button2");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment