Skip to content

Instantly share code, notes, and snippets.

@sodastsai
Created November 19, 2012 15:36
Show Gist options
  • Select an option

  • Save sodastsai/4111306 to your computer and use it in GitHub Desktop.

Select an option

Save sodastsai/4111306 to your computer and use it in GitHub Desktop.
Block and Closure
#import <Foundation/Foundation.h>
@interface BCObject : NSObject
+ (int(^)(int, int))magicFunction:(int)seed;
+ (BOOL(^)(id))lengthValidator:(NSUInteger)validLength;
@end
@implementation BCObject
+ (int(^)(int, int))magicFunction:(int)seed {
int salt = 13.0f;
int (^result) (int , int) = ^ int (int a, int b) {
return a * salt + seed * b;
};
// Copy it to heap for dynamic usage
return Block_copy(result);
}
+ (BOOL(^)(id))lengthValidator:(NSUInteger)validLength {
BOOL (^result) (id) = ^ BOOL (id object) {
if ([object respondsToSelector:@selector(length)]) {
return [object length]==validLength;
} else if ([object respondsToSelector:@selector(count)]) {
return [object count]==validLength;
} else {
return NO;
}
};
// Copy it to heap for dynamic usage
return [[result copy] autorelease];
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// You cannot release the block ... bad
//NSLog(@"%d", [BCObject magicFunction:19](1, 3));
// You can release the block then ... good.
int (^magic)(int, int) = [BCObject magicFunction:20];
NSLog(@"%d", magic(12, 13));
Block_release(magic);
NSArray *array1 = @[@1, @2.5f, @YES];
NSArray *array2 = @[@1, @3];
// Blocks are already in the autorelease pool.
NSLog(@"Array 1 is %@" , [BCObject lengthValidator:3](array1)?@"valid":@"invalid");
NSLog(@"Array 2 is %@" , [BCObject lengthValidator:3](array2)?@"valid":@"invalid");
}
return 0;
}
#import <Foundation/Foundation.h>
@interface BCObject : NSObject
+ (int(^)(int, int))magicFunction:(int)seed;
+ (BOOL(^)(id))lengthValidator:(NSUInteger)validLength;
@end
@implementation BCObject
+ (int(^)(int, int))magicFunction:(int)seed {
int salt = 13.0f;
return ^ int (int a, int b) {
return a * salt + seed * b;
};
}
+ (BOOL(^)(id))lengthValidator:(NSUInteger)validLength {
return ^ BOOL (id object) {
if ([object respondsToSelector:@selector(length)]) {
return [object length]==validLength;
} else if ([object respondsToSelector:@selector(count)]) {
return [object count]==validLength;
} else {
return NO;
}
};
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"%d", [BCObject magicFunction:19](1, 3));
int (^magic)(int, int) = [BCObject magicFunction:20];
NSLog(@"%d", magic(12, 13));
NSArray *array1 = @[@1, @2.5f, @YES];
NSArray *array2 = @[@1, @3];
NSLog(@"Array 1 is %@" , [BCObject lengthValidator:3](array1)?@"valid":@"invalid");
NSLog(@"Array 2 is %@" , [BCObject lengthValidator:3](array2)?@"valid":@"invalid");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment