block的简单使用

一: 定义block 初始化

#import <UIKit/UIKit.h>

 

@interface LHQDemoView : UIView

- (instancetype)initWithFrame:(CGRect)frame andCompelete:(void(^)(NSString *msg))block;

 

 

- (instancetype)initWithFrame:(CGRect)frame andCompelete:(void(^)(NSString *msg))block{

    if(self = [super initWithFrame:frame]){

        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];

        [btn setTitle:@"提示" forState:UIControlStateNormal];

        [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];

        [self addSubview:btn];

        self.block = block;

    }

    return self;

}

 

 

 

 

二: 定义全局block

@interface LHQDemoView()

//block定义的时候一定要用copy

/*

 block默认在栈中  栈中内存归系统管理

 系统管理有个弊端:到作用于结束就被干掉

 执行了一个copy操作之后,就会把block从栈中放到堆中

 会自动有一个强引用来指向它

 

 

 */

@property(nonatomic,copy)void(^block)(NSString *);

 

设置

self.block = block;

 

 

 

 

三: 给block赋值

- (void)btnClicked: (UIButton *)btn{

    self.block(@"点击了某个按钮");

    NSLog(@"btnClicked");

}

 

 

四: 使用

  导入头文件

#import "LHQDemoView.h"

@interface ViewController ()

 

@end

 

 

 LHQDemoView *demoView = [[LHQDemoView alloc]initWithFrame:CGRectMake(100, 200, 100, 100) andCompelete:^(NSString *msg) {

        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];

        [alert show];

    }];

    [self.view addSubview:demoView];

 

 

 

 

 

 

 

posted @ 2017-06-27 17:46  李洪强  阅读(206)  评论(0编辑  收藏  举报