Block基础知识

Block学习(一)函数

(一)block的一些理解学习

(1)“回调函数”的理解:ui

好比说有A、B两个类,block的声明和调用都在A类,而block在B类实现;B类中没有调用block的权限,最终须要A类触发调用,这是我在学习过程当中看到的一种理解方式,我的以为很形象。spa


(2)block和delegate的比较:code

首先须要说明的一点就是无论是block仍是delegate均可以做为回调函数。对象

delegate必须指定委托对象,定义委托协议;委托对象须遵照委托协议,并实现协议中的@required方法;回调函数

block只需声明block回调函数,实现函数便可。
it


(二)本身写的一些block实例io


(1)有返回值的block实例class

//block在excuteBlock执行函数外实现
typedef NSString* (^changeColor)(CGRect rect,UIColor *color);
-(NSString *)chageView:(CGRect)frame ByColor:(UIColor *)color FromBlock:(changeColor)chageColorBlock {
    
   return chageColorBlock(frame,color);
}

changeColor chageBgColor = ^(CGRect frame,UIColor *color) {
    
    UIView *testVC = [[UIView alloc] initWithFrame:frame];
    testVC.backgroundColor = color;
    
    return @"成功";
};


//block在excuteBlock执行函数内实现
typedef NSString* (^chageColorInline)(CGRect rect,UIColor *color);
-(NSString *)chageView:(CGRect)frame ByColor:(UIColor *)color FromInlineBlock:(chageColorInline) chageColorByInlineBlock {
    
    return chageColorByInlineBlock(frame,color);
}

-(void)excuteBlock {
    
    [self chageView:({
        
        CGRect frame = CGRectZero;
        frame;
        
    }) ByColor:[UIColor redColor] FromBlock:chageBgColor];
    
    chageColorInline changeBgColorInline = ^(CGRect frame,UIColor *color) {
        
        UIView *testVC = [[UIView alloc] initWithFrame:frame];
        testVC.backgroundColor = color;
        
        return @"成功";
    };
    
    [self chageView:({
        
        CGRect frame = CGRectZero;
        frame;
        
    }) ByColor:[UIColor greenColor] FromInlineBlock:changeBgColorInline];
}


(2)无返回值的block实例

//block回调实例
typedef void (^noticeOthersBlock)(void);
-(void)excuteRetBlock {
    NSLog(@"开始执行");
    NSLog(@"正在执行");
    
    noticeOthersBlock returnBlock = ^{
        
        NSLog(@"执行完其余任务后,回调");
    };
    
    [self dosomethingByBlock:returnBlock];
}

//执行完毕,回调
-(void)dosomethingByBlock:(noticeOthersBlock)otherBlock {
    
    NSLog(@"执行完毕");
    otherBlock();
}


(3)block回调

回调函数的声明和调用;

//MyBlock.h
@interface MyBlock : NSObject

typedef void (^addResult)(NSInteger result);

-(void)addOperFirstprama:(NSInteger)first bySecprama:(NSInteger)second result:(addResult)result;
@end


//MyBlock.m
#import "MyBlock.h"

@implementation MyBlock

-(void)addOperFirstprama:(NSInteger)first bySecprama:(NSInteger)second result:(addResult)result {
    
    NSInteger oper = first + second;
    
    result(oper);
}
@end


回调函数的定义;

//执行回调的主体MyBlock对象(也就是上面说的A类)
-(void)spendResult {
    
    MyBlock *block = [[MyBlock alloc] init];
    
    [block addOperFirstprama:5 bySecprama:7 result:^(NSInteger result) {
        
        if (result == 12) {
            
            NSLog(@"正确");
        }
        
        else {
        
            NSLog(@"错误");
        }
    }];
}

执行[self spendResult],输出“正确”。

相关文章
相关标签/搜索