OC语言学习23-Block在类中的应用

来源:互联网 发布:床垫哪个品牌好 知乎 编辑:程序博客网 时间:2024/05/28 01:36

创建Mother类和OldWoman类:

Mother.h中的代码:

#import <Foundation/Foundation.h>


@interface Mother : NSObject


@property(nonatomic,copy)NSString *name;

//block作为属性运用

@property(nonatomic,copy)void(^actionBlock)();


//block当参数传递

-(void)goOutsideWithAction:(void (^)())action;


-(void)cooking;

@end


Mother.m中的代码:

#import "Mother.h"


@implementation Mother


-(void)goOutsideWithAction:(void (^)())action

{

    NSLog(@"去上班了");

    action();

}


-(void)cooking

{

    NSLog(@"我去做饭了");

 //   self.actionBlock();

    if(self.actionBlock) {

        self.actionBlock();

    }

}

@end

OldWoman.h中的代码:

#import <Foundation/Foundation.h>


@interface OldWoman : NSObject


-(void)lookAfterBaby;


@end

OldWoman.m中的代码:

#import "OldWoman.h"


@implementation OldWoman


-(void)lookAfterBaby

{

    NSLog(@"我帮你照顾宝宝");

}

@end


main.m中代码

#import <Foundation/Foundation.h>

#import "Mother.h"

#import "OldWoman.h"


int main(int argc,const char * argv[]) {

    @autoreleasepool {

        Mother *mother = [[Motheralloc] init];

        OldWoman *oldWoman = [[OldWomanalloc] init];

        /*mother执行goOutsideWithAction方法后

        通知oldWoman执行lookAfterBaby方法*/

        [mother goOutsideWithAction:^{

            [oldWoman lookAfterBaby];

        }];

        /*因为block作为属性自动生成settergetter方法

         mother可以直接执行setActionBlock方法然后

         通知oldWoman执行lookAfterBaby方法*/

        [mother setActionBlock:^{

            [oldWoman lookAfterBaby];

        }];

        [mother cooking];

    }

    return0;

}



原创粉丝点击