Skip to content

Instantly share code, notes, and snippets.

@chapados
Created June 18, 2011 20:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chapados/1033477 to your computer and use it in GitHub Desktop.
Save chapados/1033477 to your computer and use it in GitHub Desktop.
yield(self) pattern implemented with objective-C blocks
//
// yield(self) pattern implemented using objective-C blocks
// (not as pretty as Ruby...)
//
// compile:
// llvm-gcc-4.2 -o yield-self -framework Foundation yield-self.m
#import <Foundation/Foundation.h>
@class MyClass;
typedef id (^YieldSelfBlock)(MyClass *instance);
@interface MyClass : NSObject
{
NSString* _name;
}
@property (nonatomic, copy) NSString *name;
+ (id)instanceUsingBlock:(YieldSelfBlock)block;
+ (id)newUsingBlock:(YieldSelfBlock)block;
- (id)initUsingBlock:(YieldSelfBlock)block;
@end
@implementation MyClass
@synthesize name = _name;
+ (id)instanceUsingBlock:(YieldSelfBlock)block
{
return [[[self alloc] initUsingBlock:block] autorelease];
}
+ (id)newUsingBlock:(YieldSelfBlock)block
{
return [[self alloc] initUsingBlock:block];
}
- (id)initUsingBlock:(YieldSelfBlock)block;
{
if ( (self != [super init]) )
{
[self release];
return nil;
}
if ( block )
block(self);
return self;
}
- (void)dealloc
{
[_name release]; _name = nil;
[super dealloc];
}
@end
int main(int argc, char** argv)
{
MyClass *example = [MyClass newUsingBlock:^id (MyClass *obj){
obj.name = @"Brian";
}];
NSLog(@"example: %@; name = %@", example, example.name);
[example release];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment