block相似C語言的函數指針,但Blocks不是一個指針,而是一個不帶名字的函數(匿名的代碼塊)。在這裏我就不贅述了,說說將UIAlertView的按鈕點擊代理方式改成Block形式。代碼中定義的全局變量_index與本文主要內容無關,在下一篇,我會詳細說明Block的相互引用問題函數
//控制器ViewController.h文件atom
1 #import <UIKit/UIKit.h> 2 3 @interface ViewController : UIViewController 4 5 { 6 NSInteger _index; 7 } 8 9 @property (nonatomic, assign)NSInteger index; 10 11 @end
#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的類spa
//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
#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形式,就是這些內容了。指針