首页 编程 软件学院 查看内容

iOS 使用Block实现函数回调

2014-11-11 11:09 1087 0

摘要: 其实,iOS中的Block就是C++中的函数指针,实现方式都是一样的,下面贴出一个简单的实践。首先,创建一个回调的类BlockStudy.h[objc] view plaincopyprin...
关键词: nbsp BlockStudy ViewController TestBlock 杜甲 void Block plaincopyprint import StartBlock

其实,iOS中的Block就是C++中的函数指针,实现方式都是一样的,下面贴出一个简单的实践。首先,创建一个回调的类BlockStudy.h[objc] view plaincopyprint?//  //  BlockStudy.h  //  BlockStudy  //  //  Created by 杜甲 on 11/11/14.  //  Copyright (c) 2014 杜甲. All rights reserved.  //    #import <Foundation/Foundation.h>    @interface BlockStudy : NSObject    typedef void (^TestBlock)();  @property (nonatomic , strong) TestBlock testBlock;      - (void)StartBlock;  @end  BlockStudy.m[objc] view plaincopyprint?//  //  BlockStudy.m  //  BlockStudy  //  //  Created by 杜甲 on 11/11/14.  //  Copyright (c) 2014 杜甲. All rights reserved.  //    #import "BlockStudy.h"    @implementation BlockStudy    - (void)test  {      if (_testBlock) {          _testBlock();      }  }    - (void)StartBlock  {      [self performSelector:@selector(test) withObject:nil afterDelay:2.0];  }    @end  调用类ViewController.m[objc] view plaincopyprint?//  //  ViewController.m  //  BlockStudy  //  //  Created by 杜甲 on 11/11/14.  //  Copyright (c) 2014 杜甲. All rights reserved.  //    #import "ViewController.h"  #import "BlockStudy.h"    @interface ViewController ()    @end    @implementation ViewController    - (void)viewDidLoad {      [super viewDidLoad];      // Do any additional setup after loading the view, typically from a nib.      BlockStudy *block = [[BlockStudy alloc] init];      block.testBlock = ^()      {          UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Block学习" message:@"测试成功" delegate:self cancelButtonTitle:@"取消吧" otherButtonTitles:@"OK", nil nil];          [alert show];                };      [block StartBlock];  }    - (void)didReceiveMemoryWarning {      [super didReceiveMemoryWarning];      // Dispose of any resources that can be recreated.  }    @end  
声明:文章版权归原作者所有 部分文章转自互联网 如有侵权请联系 [邮箱地址] 删除

路过

雷人

握手

鲜花

鸡蛋

最新评论

返回顶部