object c block

来源:互联网 发布:下载一个淘宝网 编辑:程序博客网 时间:2024/04/29 20:25
////  main.m//  Block////  Created by 千雅爸爸 on 16/10/7.//  Copyright © 2016年 kodulf. All rights reserved.//#import <Foundation/Foundation.h>#import "Parent.h"#import "Guider.h"//c语言函数支针void test(){    printf("%s\n",__func__);}int main(int argc, const char * argv[]) {    @autoreleasepool {        //相当于c语言的函数指针        void (*testPtr)() = test;        //使用函数指针调用函数;        test();        testPtr();                //如何去声明block,注意block 是在main函数的内部的        void (^testBlock)() = ^(){            test();            NSLog(@"info");        };        //调用block        testBlock();                int __block number =2;//要想在block 中使用必须要添加__block        //为什么这里使用的是int,而不是nsinteger        int (^sumBlock)(int,int) = ^(int a, int b){            number = 3;            return a+b;        };        NSLog(@"sum = %d",sumBlock(1,2));                NSLog(@"number=%d",number);                //++++block 在类中的使用+++++++++        Parent *parent = [[Parent alloc] init];        Guider *guider = [[Guider alloc]init];        //block作为参数        [parent goOutSideWithAction:^{            [guider lookafterBaby];        }];        //block作为属性,因为是property 所以可以使用set,然后把block放在参数里面        [parent setActionBlock:^{            [guider lookafterBaby];        }];        [parent cooking];    }    return 0;}


Parent.h

////  Parent.h//  Block////  Created by 千雅爸爸 on 16/10/7.//  Copyright © 2016年 kodulf. All rights reserved.//#import <Foundation/Foundation.h>@interface Parent : NSObject@property (nonatomic,copy) NSString *name;//家长出门,需要另外一个人去帮忙看一下小孩,需要两个类进行交互的时候,可以考虑用block//有两种方式,第一个作为行参,第二个是作为让block 做为类的属性进行出现-(void)goOutSideWithAction:(void (^)())action;@property (nonatomic,copy) void (^actionBlock)();//必须是copy-(void)cooking;@end

////  Parent.m//  Block////  Created by 千雅爸爸 on 16/10/7.//  Copyright © 2016年 kodulf. All rights reserved.//#import "Parent.h"@implementation Parent-(void)goOutSideWithAction:(void (^)())action{    NSLog(@"家长出门了");    //block的实现部分和调用部分进行分离    action();}-(void)cooking{    NSLog(@"家长开始做饭了,cooking");    if(self.actionBlock){//首先判断是否存在        self.actionBlock();    }}@end

////  Guider.h//  Block////  Created by 千雅爸爸 on 16/10/7.//  Copyright © 2016年 kodulf. All rights reserved.//#import <Foundation/Foundation.h>@interface Guider : NSObject-(void)lookafterBaby;@end

////  Guider.m//  Block////  Created by 千雅爸爸 on 16/10/7.//  Copyright © 2016年 kodulf. All rights reserved.//#import "Guider.h"@implementation Guider-(void)lookafterBaby{    NSLog(@"Guider 看护小孩");}@end

http://blog.csdn.net/rodulf/article/details/52750955

1.Java代码说明blcok就是Java中匿名内部类,而匿名内部类的好处是代码更清晰例如button btn = new Button().setListener(newListener(){//  这里写上监听的代码,这样就可以很直观的观察到这个btn要干啥了//  例如这里写个发送邮件的代码,这样人们就知道你这按钮是点击后是发    //送邮件的功能});






0 0
原创粉丝点击