Skip to content

Instantly share code, notes, and snippets.

@PsychoH13
Created September 24, 2009 14:58
Show Gist options
  • Save PsychoH13/192781 to your computer and use it in GitHub Desktop.
Save PsychoH13/192781 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
@implementation NSArray (BlocksTest)
- (void) do:(void (^)(id))aBlock;
{
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
aBlock(obj);
}];
}
- (id) inject:(id)aValue into:(id (^)(id, id))aBlock;
{
__block id sum = aValue;
[self do:^(id each)
{
[sum autorelease];
sum = [aBlock(sum, each) retain];
}];
return [sum autorelease];
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
id array = [NSArray arrayWithObjects:@"first", @"second", @"third", nil];
// [array do:^(id each){
// NSLog(@"%@", each);
// }];
//
// crashes, why?
NSLog(@"%@", [array inject:@"" into:^(id concatenation, id element)
{
id ret = [concatenation stringByAppendingString:element];
return ret;
}]);
[pool drain];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment