block类似C语言的函数指针,但Blocks不是一个指针,而是一个不带名字的函数(匿名的代码块)。在这里我就不赘述了,说说将UIAlertView的按钮点击代理方式改为Block形式。代码中定义的全局变量_index与本文主要内容无关,在下一篇,我会详细说明Block的相互引用问题
//控制器ViewController.h文件
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
NSInteger _index;
}
@property (nonatomic, assign)NSInteger index;
@end
//ViewController.m文件
#import "ViewController.h"
#import "MyAlerView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//在MRC中解决相互引用的问题,用__block 定义一个当前的控制器类型
//相信很多人都对Block是如何相互引用比较关心,分析block在copy全局变量_index是,为了保证其不被销毁,将持有_index属性的对象(viewController)也copy了一份 (注:在这里如果只是将UIAlertView的按钮点击代理方式改为Block形式,没必要关心下面两行代码)
__block ViewController *VCblock = self;
self.index = 90;
//子类化创建
MyAlerView *alert = [[MyAlerView alloc]initWithTitle:@"提示" message:@"玩吧" cancelButtonTitle:@"取消" otherButtonTitles:@"确定" clickButton:^(NSInteger index){
if (index == 1) {
NSLog(@"确定");
NSLog(@"%ld",VCblock->_index);
}
else if (index == 0)
NSLog(@"取消");
}];
[alert show];
[alert release];
}
//新建的继承自 UIAlertView 的类
//MyAlerView.h
#import <UIKit/UIKit.h>
//注(这里的MyBlock是类型名,而不是变量名)
typedef void (^MyBlock)(NSInteger index);
@interface MyAlerView : UIAlertView
@property (nonatomic, copy)MyBlock block;
//构造一个没有代理的初始化方法,并将Myblock类型加上
- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles clickButton:(MyBlock)block;
@end
//MyAlerView.h
#import "MyAlerView.h"
@implementation MyAlerView
- (void)dealloc
{
NSLog(@" 挂掉 ");
[super dealloc];
}
- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles clickButton:(MyBlock)block
{
self = [super initWithTitle:title message:message delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil];
if (self) {
//确定当前block为传过来的block(注:如果时在MRC这里必须用self.block)
self.block = block;
}
return self;
}
//实现按钮点击事件的协议方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
_block(buttonIndex);
}
@end
关于将UIAlertView的按钮点击代理方式改为Block形式,就是这些内容了。