Using blocks instead of delegates in Objective C

Delegates are a very simple and straight forward feature in objective C. Some of its usage scenarios can be when you want to pass data between two controllers, or set a value when something happens..etc. You can do the same using blocks.
Disclaimer: I am not trying to compare between these two programming techniques.
In my main controller, I have a method known as addText :
[code language=”objc”]
-(void) addText {
RDTextViewController *controller = [[RDTextViewController alloc] init];
[[RDHelper navigationController] pushViewController:controller animated:YES];
controller.setText = ^(NSString *string){
if([string length] > 0){
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, self.view.frame.size.width-10, 200)];
[label setText:string];
[label setUserInteractionEnabled:YES];
[label setLineBreakMode:NSLineBreakByWordWrapping];
[label setNumberOfLines:0];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[label addGestureRecognizer:pan];
[baseView addSubview:label];
}
};
}
[/code]
In the above example code, I call a controller RDTextViewController and then when this returns, I basically set the text in a new view.
Over here “setText” is my block. Its signature is a NSString. I will define it below:
[code language=”objc”]
#import <UIKit/UIKit.h>
@interface RDTextViewController : UIViewController<UITextViewDelegate>
@property (nonatomic, copy) void (^setText)(NSString *text);
@end
// .m
@interface RDTextViewController ()
{
UITextView *textView;
}
@end
@implementation RDTextViewController
@synthesize setText;
-(void) doneButton {
if(setText){
self.setText(textView.text);
}
[[RDHelper navigationController] popViewControllerAnimated:YES];
}
[/code]
As you can see above when the doneButton is pressed, I just set the value. Another easy way to set values in between controllers and different objects.

One response

Leave a Reply

Your email address will not be published. Required fields are marked *