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],輸出「正確」。

相關文章
相關標籤/搜索