码迷,mamicode.com
首页 > 其他好文 > 详细

block和代理使用对比

时间:2016-02-27 18:00:02      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

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和代理使用对比

标签:

原文地址:http://www.cnblogs.com/mengdaxia117/p/5223083.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!