程序员iOS开发攻城狮的集散地iOS面试题

iOS Block和代理的区别与使用

2018-05-17  本文已影响88人  朝雨晚风

理论知识点

1、在.h中声明代理和block

#import <Foundation/Foundation.h>
//  声明一个delegate和block
typedef void(^clickBackBlock)(void);

@protocol Block_DelegateClass <NSObject>
- (void)clickBackDelegate;
@end

@interface Block_DelegateClass : NSObject

@property (nonatomic, weak) id<Block_DelegateClass> delegatel;

@property (nonatomic, copy) clickBackBlock block;

- (void)doSomething;
@end

2、doSomething中让他的代理去实现

#import "Block_DelegateClass.h"

@implementation Block_DelegateClass

- (void)doSomething {
    
    /**
     * block和代理的调用区别
     */
    if (self.block) {   //  判断block是否指向了某个block实体 ^(传入参数列){行为主体};
        self.block();  //  执行指向的block实体的代码块 ^{}
    }
    
    if (self.delegatel) {  //  判断delegate是否有对象赋值
        [self.delegatel clickBackDelegate];  // 调用代理方法
    }
}

@end

3、外部的某个类成为A类的代理


#import "OneViewController.h"
#import "Block_DelegateClass.h"

@interface OneViewController ()<Block_DelegateClass>

@property(nonatomic, strong) Block_DelegateClass *blockAnddeleagate;

@end

@implementation OneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _blockAnddeleagate = [[Block_DelegateClass alloc] init];
    
    _blockAnddeleagate.block = ^{   // 让block指向一个实体代码块,等待被调用时候执行
        NSLog(@"我是block体,我替别人doSomething");
    };
    
    _blockAnddeleagate.delegatel = self;  //  self 成为代理对象
    
    
    [self callMethod];
    // Do any additional setup after loading the view.
}

#pragma mark - Block_DelegateClass

// 实现代理方法
- (void)clickBackDelegate {
    NSLog(@"我是代理,我替别人doSomething");
}

#pragma mark - event Method

- (void)callMethod {
    [_blockAnddeleagate doSomething];
}

@end
上一篇下一篇

猜你喜欢

热点阅读