Change the Protocol to block, run, set a header file person. h
#import <Foundation/Foundation.h>@interface Person : NSObject@property (nonatomic, copy) void (^brak)(void); //声明void类返回void的block类型的brak,@property (nonatomic, copy) void (^tail)(void); //@property同时声明变量@property (nonatomic, copy) void (^run)(void);- (void)playwithanimal; //一个实例方法@end
M file write Method
#import "Person.h"@implementation Person- (void)playwithanimal //编写方法{ if(_brak) //如果_brak对像飞空,则_brak(),这_brak就是^block声明的方法 _brak(); if(_tail) _tail(); if(_run) _run(); }@end
Finally, run it in the mian file.
#import "ViewController.h"#import "Person.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. Person * person = [[Person alloc]init]; //person类中声明一个对象并初始化分配内存空间. person.brak = ^{ //person指向brak的地址.block返回void,打印出字符 NSLog(@"wang wang"); //但是有个缺点,就是同样的brak,结果内容只能是一样的wangwang;
//如果通过协议,可以通过两个其他类而得到一个事例一样的方法中,实行的结果不一样 }; person.tail = ^{ NSLog(@"roking tail"); }; person.run = ^{ NSLog(@"the animal is running"); }; [person playwithanimal]; //调用方法playwithanimal,则会运行其中的block,block返回 //中则会打印相关内容}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}@end
Change protocol exercise to block