Change protocol exercise to block

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.