block和代理使用对比
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了block和代理使用对比相关的知识,希望对你有一定的参考价值。
demo设计:做简单的抽奖,在viewcontroller中调用代理和block去获得抽奖号码,在viecontroller中打印出来。
代理类的.h文件
@protocol DelegateClassDelegate; @interface DelegateClass : NSObject @property(nonatomic,weak) id<DelegateClassDelegate> delegate; -(void)dosomthing; @end @protocol DelegateClassDelegate <NSObject> -(void)DelegateClass:(DelegateClass *)delegateClass passNum:(NSUInteger)num; @end
代理类的.m 文件
@implementation DelegateClass -(void)dosomthing{ NSUInteger random = arc4random()%100; [self.delegate DelegateClass:self passNum:random]; } @end
block 类的.h文件
@interface BlockClass : NSObject -(void)dosomething:(void (^)(NSUInteger num))passnumblock; @end
block类的.m文件
@implementation BlockClass -(void)dosomething:(void (^)(NSUInteger num))passnumblock{ NSUInteger random = arc4random()%100; passnumblock(random); } @end
在viewcontroller中调用
#import "ViewController.h" #import "DelegateClass.h" #import "BlockClass.h" @interface ViewController ()<DelegateClassDelegate> @property(nonatomic,strong) DelegateClass *delegateClass; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.delegateClass = [[DelegateClass alloc] init]; self.delegateClass.delegate = self; //触发方法 [self.delegateClass dosomthing]; BlockClass *block = [[BlockClass alloc] init]; [block dosomething:^(NSUInteger num) { NSLog(@"通过block获得的抽奖号码是%ld",num); }]; [block dosomething:^(NSUInteger num) { NSLog(@"通过block获得的抽奖号码是%ld",num); }]; } - (void)DelegateClass:(DelegateClass *)delegateClass passNum:(NSUInteger)num{ NSLog(@"通过代理获得的抽奖号码是%ld",num); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
打印结果:
2016-02-27 15:50:08.017 delegateAndBlock[8338:1753403] 通过代理获得的抽奖号码是63
2016-02-27 15:50:08.017 delegateAndBlock[8338:1753403] 通过block获得的抽奖号码是85
2016-02-27 15:50:08.017 delegateAndBlock[8338:1753403] 通过block获得的抽奖号码是46
总结:
代理是一对一的实现,block可以实现一对多
代理的使用较为麻烦,block相对简单,并且代码的逻辑更连贯,可读性强
代理在做自定义控件时很有优势
以上是关于block和代理使用对比的主要内容,如果未能解决你的问题,请参考以下文章