TestBlock.h typedef int(^SumBlock)(int num1, int num2); #import <Foundation/Foundation.h> @interface Testblock : NSObject @property (nonatomic,copy) SumBlock sumblock; -(void)beginSum:(SumBlock)sumb; -(void)callSum; @end @implementation Testblock static Testblock *myblock = nil; + (instancetype)allocWithZone:(struct _NSZone *)zone//单例练习可以忽略 { @synchronized(self) { if (myblock == nil) { myblock = [super allocWithZone:zone]; return myblock; } } return myblock; } -(void)callSum { if (_sumblock) { int c = _sumblock(6,8); NSLog(@"%d",c); } } -(void)beginSum:(SumBlock)sumb { _sumblock = sumb; //保存block的实现,在ViewController里面实现了这个block的方法之后,回传block到这里。之后callsum调用_sumblock便能够打印出求和的值, //整个过程相当于将6和8传给了ViewController,viewc再把实现方法传回到这里。 } @end
- (void)viewDidLoad { [super viewDidLoad]; Testblock *tblock = [[Testblock alloc ]init]; Testblock *tblock1 = [[Testblock alloc ]init]; NSLog(@"%p",tblock); NSLog(@"%p",tblock1);//单例写的是否正确,可以忽略 [tblock beginSum:^int(int num1, int num2) { return num1 + num2;//实现block的方法 }]; [tblock callSum]; }
时间: 2024-10-25 04:40:45