oc通过代码块实现回调:

 1. 首先定义Singleton.h定义一个单利封装宏


// .h
#define single_interface(class)  + (class *)shared##class;

// .m
// \ 代表下一行也属于宏
// ## 是分隔符
#define single_implementation(class) \
static class *_instance; \
 \
+ (class *)shared##class \
{ \
    if (_instance == nil) { \
        _instance = [[self alloc] init]; \
    } \
    return _instance; \
} \
 \
+ (id)allocWithZone:(NSZone *)zone \
{ \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
        _instance = [super allocWithZone:zone]; \
    }); \
    return _instance; \
}

2. 定义回调工具类: 

 .h文件:

#import <Foundation/Foundation.h>
#import "Singleton.h"

typedef void(^myblock)(int a,int b);

@interface XMGLocation : NSObject


single_interface(XMGLocation);


-(void) showMessage : (myblock) block1;

@end

.m文件: 

//
//  XMGLocation.m
//  BlockTest
//
//  Created by denganzhi on 2018/6/19.
//  Copyright © 2018年 denganzhi. All rights reserved.
//

#import "XMGLocation.h"

@interface XMGLocation()

@property (nonatomic, copy) myblock block;


@property(nonatomic,strong) NSTimer* timer;


@end

@implementation XMGLocation

single_implementation(XMGLocation);


-(void) showMessage : (myblock) block1{
    self.block = block1;
    NSLog(@"%@",@"开始化妆");
    //self.block(4, 6);
    NSLog(@"%@",@"最终结果");
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
       // 这里就是回调随时可以把内部数据传递到外部去
        self.block(4, 6);
    }];
   
}

-(void)dealloc{
  
    NSLog(@"%@",@"挂了吗");
    
    [self.timer invalidate];
    self.timer=nil;
}

@end

  3.  调用代码块:

- (IBAction)clickshow:(id)sender {
    
    [[XMGLocation sharedXMGLocation] showMessage:^(int a, int b) {
        int c= a+b;
        NSLog(@"运算结果是:%d",c);
    }];
}



猜你喜欢

转载自blog.csdn.net/dreams_deng/article/details/80745648
今日推荐