您的位置:首页 > 移动开发 > IOS开发

Block - 6

2015-10-27 11:53 330 查看
学习完Block 1 - 5 相信对block 的理解和使用肯定是不存在什么问题的,但是提到一点,如何用block代替delegate,本篇将会学习到:

本文学习于 :https://github.com/pony-maggie/DelegateDemo (若侵告知必删)

分别实现block 和 delegate 的类:

头文件:

#import <Foundation/Foundation.h>

//委托的协议定义
@protocol UpdateAlertDelegate <NSObject>
- (void)updateAlert;
@end

@interface TimerControl : NSObject
//委托变量定义
@property (nonatomic, weak) id<UpdateAlertDelegate> delegate;

//block
typedef void (^UpdateAlertBlock)();
@property (nonatomic, copy) UpdateAlertBlock updateAlertBlock;

- (void) startTheTimer;

@end


delegate实现:

#import "TimerControl.h"

@implementation TimerControl

- (void) startTheTimer
{
[NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(timerDelegateProc) userInfo:nil repeats:NO];
}

- (void) timerDelegateProc
{
if ([self.delegate respondsToSelector:@selector(updateAlert)])
{
[self.delegate updateAlert];
}
}

@end

#import "DelegateDemoViewController.h"

@interface DelegateDemoViewController () <UpdateAlertDelegate>

@end

@implementation DelegateDemoViewController

- (void)viewDidLoad
{
[super viewDidLoad];

TimerControl *timer = [[TimerControl alloc] init];

timer.delegate = self; //设置委托实例

[timer startTheTimer];//启动定时器,定时5触发
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}

//"被委托对象"实现协议声明的方法,由"委托对象"调用
- (void)updateAlert
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"时间到" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];

alert.alertViewStyle=UIAlertViewStyleDefault;
[alert show];
}

@end

 ---------------------分割线

block实现:

#import "TimerControl.h"

@implementation TimerControl

- (void) startTheTimer
{
[NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(timerBlockProc) userInfo:nil repeats:NO];
}

- (void) timerBlockProc
{
//block代替委托
if (self.updateAlertBlock)
{
self.updateAlertBlock();
}
}

@end

#import "DelegateDemoViewController.h"

@interface DelegateDemoViewController ()

@end

@implementation DelegateDemoViewController

- (void)viewDidLoad
{
[super viewDidLoad];

TimerControl *timer = [[TimerControl alloc] init];

//实现block
timer.updateAlertBlock = ^()
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"时间到" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];

alert.alertViewStyle=UIAlertViewStyleDefault;
[alert show];
};

[timer startTheTimer];//启动定时器,定时5触发
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}

@end


看完例子,对它们的区别一目了然吧!block更加简洁,直观,灵活! 本质上其实都是用了“反射“的原理。结构上也是非常相像,例如判断处,和实现处。

除了使用上的简洁简便上,最重要的一点是拜托了delegate使用上必须对象化的枷锁,delegate声明代理,实现,设置代理,维护协议等等繁琐并且与对象相关度强的麻烦,在block上并可以一一纫解,这也是block灵活的强大之处。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS block delegate