iOS学习(OC语言)知识点整理
一、Block 的介绍 1)概念: block 是一种数据类型,类似于C语言中没有名字的函数,可以接收参数,也可以返回值与C函数一样被调用
封装一段代码 可以在任何地方调用 block 也可以作为函数参数,以及函数返回值
2)Block 实例代码 1//定义了一个block类型MyBlock,MyBlock类型的变量只能指向带两个int的参数和返回int的代码块2typedefint(^MyBlock)(int,int);3//定义一个函数指针4int(*pMath)(int,int);56intadd(inta,intb)7{8returna+b;9}1011intsub(inta,intb)12{13returna-b;14}1516intmain(intargc,constchar*argv[]) {17@autoreleasepool {18pMath = add;//指向函数指针19//NSLog(@"sum: %d",pMath(2,3));20pMath =sub;2122//定义了一个block,block只能指向带2个int的参数,返回int的代码块23//以^开始的为代码块,后面()是参数,然后{}代码块24int(^bloke1)(int,int) = ^(inta,intb){25returna+b;26};2728ints = bloke1(3,5);29NSLog(@"s:%d",s);30//定义一个block指向没有参数没有返回值的代码块(没有参数,void可以省略)31void(^block2)(void) = ^{32NSLog(@"PRograming is fun!");33};34block2();35int(^block3)(int,int) = ^(inta,intb ){36returna-b;3738};3940//定义了MyBlock类型的变量,赋值代码块41MyBlock block4 = ^(inta,intb){42returna*b;43};4445NSLog(@"%d",block4(2,5));4647intc =10;48__blockintd =1;49//block块可以访问块外的变量但是不能修改,如果需要修改,变量前加上__block修饰50void(^block5)(void) = ^{51d = d+2;52NSLog(@"c:%d,d:%d",c,d);53};54block5();55}56return0;57}
3)解决Block互为强引用时的警告的方法 例如:1UIImageView *imgv = [[UIImageView alloc]initWithFrame:CGRectMake(10,50,300,150)];2[self.view addSubview:imgv];34//使用 __unsafe_unretained 重新定义对象 解决互为强引用的问题5__unsafe_unretained UIImageView *weakImagev =imgv;6[imgv setImageWithURL:[NSURL URLWithString:@"http://xxx/xxx.jpg?570x300_120"] withPlaceHolder:nil7competion:^(UIImage *image) {8weakImagev.image =image;9}];
4)有返回值的Block的使用方法 实例代码:
//将局部变量声明为__block,表示将会由block进行操作,比如:__blockfloatprice =1.99;float(^finalPrice)(int) = ^(intquantity)
{returnquantity *price;
};intorderQuantity =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