您的位置:首页

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);}@end
Person.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;@end
Person.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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: