iOS学习(OC语言)知识点整理
block 是一种数据类型,类似于C语言中没有名字的函数,可以接收参数,也可以返回值与C函数一样被调用
封装一段代码 可以在任何地方调用 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 }
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:@"xxx/xxx.jpg?570x300_120"] withPlaceHolder:nil 7 competion:^(UIImage *image) { 8 weakImagev.image = image; 9 }];
//将局部变量声明为__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
转载于:.html
本文发布于:2024-02-04 05:19:59,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170700000352466.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |