首页 > 代码库 > 协议练习改成block

协议练习改成block

更改协议成block,运行,设置一个头文件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文件中写方法

#import "Person.h"@implementation Person- (void)playwithanimal               //编写方法{    if(_brak)                       //如果_brak对像飞空,则_brak(),这_brak就是^block声明的方法        _brak();    if(_tail)        _tail();    if(_run)        _run();   }@end

 最后在mian文件中运行

#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

 

协议练习改成block