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

时间:2021-10-02 18:24:18

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

一、Block 的介绍

1)概念:

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

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

2)Block 实例代码

 //定义了一个block类型MyBlock,MyBlock类型的变量只能指向带两个int的参数和返回int的代码块
typedef int (^MyBlock)(int,int);
//定义一个函数指针
int (*pMath)(int ,int); int add(int a,int b)
{
return a+b;
} int sub(int a,int b)
{
return a-b;
} int main(int argc, const char * argv[]) {
@autoreleasepool {
pMath = add;//指向函数指针
//NSLog(@"sum: %d",pMath(2,3));
pMath = sub; //定义了一个block,block只能指向带2个int的参数,返回int的代码块
//以^开始的为代码块,后面()是参数,然后{}代码块
int (^bloke1)(int,int) = ^(int a,int b){
return a+b;
}; int s = bloke1(,);
NSLog(@"s:%d",s);
//定义一个block指向没有参数没有返回值的代码块(没有参数,void可以省略)
void (^block2)(void) = ^{
NSLog(@"programing is fun!");
};
block2();
int (^block3)(int,int) = ^(int a,int b ){
return a-b; }; //定义了MyBlock类型的变量,赋值代码块
MyBlock block4 = ^(int a,int b){
return a*b;
}; NSLog(@"%d",block4(,)); int c = ;
__block int d = ;
//block块可以访问块外的变量但是不能修改,如果需要修改,变量前加上__block修饰
void (^block5)(void) = ^{
d = d+;
NSLog(@"c:%d,d:%d",c,d);
};
block5();
}
return ;
}

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

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

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

//将局部变量声明为__block,表示将会由block进行操作,比如:
__block float price = 1.99;
float (^finalPrice)(int) = ^(int quantity)
{
return quantity * price;
}; int orderQuantity = ;
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