block和delegate
block和delegate是干嘛用的?為什么有這個概念?在閱讀這篇文章的時候要弄清楚。
經(jīng)常有這樣一個場景,我們調(diào)用一個方法,傳入一個參數(shù),然后在方法中根據(jù)傳遞的不同參數(shù)做不同的操作。
那么同樣會有這樣一個場景,我們調(diào)用一個方法,傳入的是一段代碼,在這個方法中,根據(jù)情況執(zhí)行這段代碼。比如說回調(diào),我們在某個方法中傳入一個回調(diào)方法,當(dāng)函數(shù)執(zhí)行完畢,再執(zhí)行回調(diào)方法。
在Android中,可以利用接口來實現(xiàn)這種傳遞代碼的操作,在iOS中用到的就是block和delegate。
Block
代碼塊,顧名思義,就是通過Block傳入一組代碼。這是一種輕量級的回調(diào),能夠直接訪問上下文,使用塊的地方和塊的實現(xiàn)地方在同一個地方,使得代碼組織更加連貫。
Delegate
委托或者說代理,委托是協(xié)議的一種,顧名思義,就是委托他人幫自己去做事。跟Block相比,是一個重量級的回調(diào)。方法的聲明和實現(xiàn)分離開來,代碼的連貫性不是很好,但是可以同時傳遞多組函數(shù),方便在不同時候調(diào)用。
代碼對比
說了區(qū)別,還是會有些抽象,在這里還是用代碼做個對比吧。
首先需要一個Test類
Test.h
#import <Foundation/Foundation.h>
//Delegate 協(xié)議
@protocol LifeDelegate<NSObject>
- (void)start;
- (void)end;
@end
@interface Test : NSObject
//Block
typedef void (^LifeBlock)();
//傳遞進來的接收值
@property (nonatomic, copy) LifeBlock block;
@property (nonatomic, weak) id<LifeDelegate> delegate;
- (void) lifeByBlock;
- (void) lifeByDelegate;
@end
Test.m
@implementation Test
- (void) lifeByBlock{
self.block();
}
- (void) lifeByDelegate{
[self.delegate start];
[self.delegate end];
}
@end
Delegate可以理解為一個協(xié)議,在需要的地方實現(xiàn)即可。關(guān)于這里有不清楚的朋友可以查看這個文章。Objective-C類別和協(xié)議
定義好Test,看一下如何使用。
ViewController
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.test = [[Test alloc] init];
self.test.delegate = self;
//這里是對Block的實現(xiàn)。
self.test.block = ^()
{
NSLog(@"block life");
};
UIButton* btnBlock = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btnBlock setFrame:CGRectMake(100, 110, 120, 40)];
[btnBlock addTarget:self action:@selector(clickBlock) forControlEvents:UIControlEventTouchUpInside];
[btnBlock setTitle:@"Block" forState:UIControlStateNormal];
btnBlock.backgroundColor=[UIColor clearColor];
[self.view addSubview:btnBlock];
UIButton* btnDelegate = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btnDelegate setFrame:CGRectMake(100, 210, 120, 40)];
[btnDelegate addTarget:self action:@selector(clickDelegate) forControlEvents:UIControlEventTouchUpInside];
[btnDelegate setTitle:@"Delegate" forState:UIControlStateNormal];
btnDelegate.backgroundColor=[UIColor clearColor];
[self.view addSubview:btnDelegate];
}
- (void)clickBlock {
[self.test lifeByBlock];
}
- (void)clickDelegate {
[self.test lifeByDelegate];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//以下是對Delegate的實現(xiàn)
- (void)start{
NSLog(@"start");
}
- (void)end{
NSLog(@"end");
}
@end
根據(jù)上述代碼,可以很清楚的理解Block和Delegate的差別。
總結(jié)
很基礎(chǔ)的一篇文章,可能很多用戶都已經(jīng)了解,但是對于初學(xué)者,還是深入理解的好。
有疑問的朋友歡迎給我留言指正,或者關(guān)注我的公眾號留言: