Last active
September 8, 2015 08:15
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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