首页 > 学院 > 开发设计 > 正文

iOS阶段学习第24天笔记(Block的介绍)

2019-11-14 18:40:06
字体:
来源:转载
供稿:网友

iOS学习(OC语言)知识点整理

一、Block 的介绍  

1)概念:

    block 是一种数据类型,类似于C语言中没有名字的函数,可以接收参数,也可以返回值与C函数一样被调用

     封装一段代码 可以在任何地方调用 block 也可以作为函数参数,以及函数返回值  

2)Block 实例代码  

 1 //定义了一个block类型MyBlock,MyBlock类型的变量只能指向带两个int的参数和返回int的代码块  2 typedef int (^MyBlock)(int,int);  3 //定义一个函数指针  4 int (*pMath)(int ,int);  5  6 int add(int a,int b)  7 {  8     return a+b;  9 }10 11 int sub(int a,int b) 12 { 13     return a-b; 14 }15 16 int main(int argc, const char * argv[]) { 17     @autoreleasepool { 18         pMath = add;//指向函数指针 19         //NSLog(@"sum: %d",pMath(2,3)); 20         pMath = sub; 21 22         //定义了一个block,block只能指向带2个int的参数,返回int的代码块  23         //以^开始的为代码块,后面()是参数,然后{}代码块 24         int (^bloke1)(int,int) = ^(int a,int b){ 25             return a+b; 26         };27 28         int s = bloke1(3,5); 29         NSLog(@"s:%d",s);  30         //定义一个block指向没有参数没有返回值的代码块(没有参数,void可以省略) 31         void (^block2)(void) = ^{ 32             NSLog(@"PRograming is fun!"); 33         }; 34         block2(); 35         int (^block3)(int,int) = ^(int a,int b ){ 36             return a-b; 37 38         }; 39 40         //定义了MyBlock类型的变量,赋值代码块 41         MyBlock block4 = ^(int a,int b){ 42             return a*b; 43         };44 45         NSLog(@"%d",block4(2,5)); 46 47         int c = 10; 48         __block int d = 1; 49         //block块可以访问块外的变量但是不能修改,如果需要修改,变量前加上__block修饰 50         void (^block5)(void) = ^{ 51             d = d+2; 52             NSLog(@"c:%d,d:%d",c,d); 53         }; 54         block5(); 55     } 56     return 0; 57 }

3)解决Block互为强引用时的警告的方法 例如:

1  UIImageView *imgv = [[UIImageView alloc]initWithFrame:CGRectMake(10, 50, 300, 150)];2     [self.view addSubview:imgv];3     4 //使用 __unsafe_unretained 重新定义对象 解决互为强引用的问题5  __unsafe_unretained UIImageView *weakImagev = imgv;6     [imgv setImageWithURL:[NSURL URLWithString:@"http://xxx/xxx.jpg?570x300_120"] withPlaceHolder:nil 7                 competion:^(UIImage *image) {8                     weakImagev.image = image;9 }];

4)有返回值的Block的使用方法 实例代码: 

//将局部变量声明为__block,表示将会由block进行操作,比如:   __block float price = 1.99; float (^finalPrice)(int) = ^(int quantity){  return quantity * price;};int orderQuantity = 10;price =0.99;NSLog(@"With block storage modifier - Ordering %d units, final price is: $%2.2f", orderQuantity, finalPrice(orderQuantity)); //此时输出为With block storage modifier – Ordering 10 units, final price is: $9.90  

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表