天天看點

将UIAlertView的按鈕點選代理方式改為Block形式

   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形式,就是這些内容了。