您的位置:首页
Block系列1:初识block
2018-03-17 21:45
375 查看
//-------1、定义函数-----//1、函数int sum(int a,int b){return a+b;}//------------------2、声明---------//2、声明函数指针【将sum换成*p就能够了】int (*p)(int a,int b);//(1)声明block【将sum换成^myBlock就能够了】int (^myBlock)(int a,int b);//举一反三void (^myBlock2)(void);- (void)viewDidLoad{[super viewDidLoad];//---------------------3、赋值【不同之处】------------------// 3、给函数指针赋值p = sum;//(2)将函数赋值给myBlock【^后面加參数列表,以及代码块内容,并以“;”结束】myBlock = ^(int a,int b){return a+b;};//---------------------4、调用------------------//4、调用int result = p(3,6);NSLog(@"%d",result);//(3)调用int resultBlock = myBlock(3,6);NSLog(@"%d",resultBlock);myBlock2 = ^(void){NSLog(@"myBlock2运行了");};myBlock2();//---------------------二、文件之间传值------------------//block的调用Person *person = [[Person alloc]init];//1-2实现block// ^int(int a, int b) {// return a+b;// }//把person的10和20传到本文件里//局部变量到block中是常量。如需改变值则须要在声明前面加 __block__block int number = 10;int resultPs = [person testMethod:^int(int a, int b) {number = 20;return a+b+number;}];//typedef 方式创建int resultPs2 = [person testMethod2:^int(int a, int b) {return a+b;}];NSLog(@"resultPs:%d resultPs2:%d",resultPs,resultPs2);}@endPerson.h
#import <Foundation/Foundation.h>//这里的PersonBlock是类型名字,能够理解为inttypedef int(^PersonBlock) (int a,int b);@interface Person : NSObject//1-1在參数中声明【int(^)(int a, int b】- (int)testMethod:( int(^)(int a, int b) )block;//这里不须要加星号- (int)testMethod2:(PersonBlock)block;@endPerson.m
#import "Person.h"@implementation Person//1-3调用block- (int)testMethod:( int(^)(int a, int b) )block{return block(10,20);}- (int)testMethod2:(PersonBlock)block{return block(1,2);}@end
相关文章推荐
- Block系列1:初识block
- Git学习系列(一)初识Git
- WPF从入门到放弃系列第一章 初识WPF
- WCF编程系列(一)初识WCF
- 解读ASP.NET 5 & MVC6系列(2):初识项目
- Android学习系列(一)初识安卓
- Microsoft Enterprise Library 5.0 系列(三) Validation Application Block (高级)
- Lucene.NET 系列之一-------------初识Lucene&&创建索引
- vagrant系列一:vagrant的安装与初识
- python 爬虫系列(0) --- 初识网络爬虫
- Unity Application Block 1.0系列(3): 属性/设值方法注入(Property/Setter Injection)
- 第4章 初识STM32—零死角玩转STM32-F429系列
- Web Client Software Factory系列(1):初识与预备知识
- 玩转Google开源C++单元测试框架Google Test系列(gtest)之一 - 初识gtest
- Microsoft Enterprise Library 5.0 系列教程(七) Exception Handling Application Block
- 从0开始学习 GitHub 系列之「初识 GitHub」
- JavaScript学习系列之初识原型继承和原型链
- 初识RabbitMQ系列之三:.net 如何使用RabbitMQ
- Javascript MVVM模式前端框架—Knockout 2.1.0系列(1):初识Ko,了解Observable与computed
- Microsoft Enterprise Library 5.0 系列(七) Exception Handling Application Block