Skip to content

Instantly share code, notes, and snippets.

@pwc3
Last active August 29, 2015 14:05
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 pwc3/9f4edc853be5a2e8f2e5 to your computer and use it in GitHub Desktop.
Save pwc3/9f4edc853be5a2e8f2e5 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
#import <stdio.h>
@interface ExampleObject : NSObject
// BLOCK AS A PROPERTY
// -------------------
//
// @property (copy, ...) return_type (^block_name)(parameter_types);
//
@property (nonatomic, copy) NSInteger (^mungeTwoIntegers)(NSInteger, NSInteger);
// BLOCK AS A METHOD PARAMETER
// ---------------------------
//
// - (...)methodName:(return_type (^)(parameter_types))methodParamName;
//
- (void)setMungeBlock:(NSInteger (^)(NSInteger, NSInteger))aBlock;
// BLOCK AS RETURN VALUE
// ---------------------
//
// - (return_type (^)(parameter_types))methodName
// - (return_type (^)(parameter_types))methodNameWithParams:...
//
- (NSInteger (^)(NSInteger, NSInteger))makeMungeBlockWithMultiplier:(NSInteger)multiplier;
@end
@implementation ExampleObject
// BLOCK AS A METHOD PARAMETER
// ---------------------------
//
// - (...)methodName:(return_type (^)(parameter_types))methodParamName;
//
- (void)setMungeBlock:(NSInteger (^)(NSInteger, NSInteger))aBlock
{
self.mungeTwoIntegers = aBlock;
self.mungeTwoIntegers = ^NSInteger (NSInteger a, NSInteger b) {
NSInteger munged = aBlock(a, b);
printf("Munging %ld and %ld returns %ld\n", a, b, munged);
return munged;
};
}
// BLOCK AS RETURN VALUE
// ---------------------
//
// Declaration: - (return_type (^)(parameter_types))methodName
// Return value: [^return_type (parameters) { ... } copy]
//
- (NSInteger (^)(NSInteger, NSInteger))makeMungeBlockWithMultiplier:(NSInteger)multiplier
{
return [^NSInteger (NSInteger a, NSInteger b) { return multiplier * (a + b); } copy];
}
@end
int main(int argc, char** argv)
{
@autoreleasepool
{
// BLOCK AS A LOCAL VARIABLE
// -------------------------
//
// LHS: return_type (^block_name)(parameter_types)
// RHS: ^return_type (parameters) { ... }
//
NSInteger (^myBlock)(NSInteger, NSInteger) = ^NSInteger (NSInteger a, NSInteger b) {
return a + b;
};
ExampleObject *obj = [ExampleObject new];
[obj setMungeBlock:myBlock];
obj.mungeTwoIntegers(3, 4);
// BLOCK AS METHOD ARGUMENT
// ------------------------
//
// [target methodName:^return_type (parameters) { ... }];
//
[obj setMungeBlock:^NSInteger (NSInteger a, NSInteger b) {
return (a * a) + (b * b);
}];
obj.mungeTwoIntegers(3, 4);
[obj setMungeBlock:[obj makeMungeBlockWithMultiplier:7]];
obj.mungeTwoIntegers(3, 4);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment