iOS开发之Block
1.什么是block,block的作用
UI开发和网络常见功能实现回调, 按钮的事件处理方法是回调方法, 网络下载后的回调处理
(1) 按钮 target-action 一个方法传入按钮中
(2) 表格视图 传入一个指针self, 回调视图控制器中的方法
(3) block 语句块, 解决回调, 理解为"匿名函数", 定义在方法里面
2.block的基本使用(语法)
涉及知识点:
定义block变量,定义block语句块
block参数和返回值
block捕获外部变量(包括self)
//block 理解匿名函数 // //1.block变量的定义 //技巧: 解决语法诡异带来难写的问题语法诡异 //定义block,^表示定义block //技巧: 函数名左右加括号,在函数名前面再加^ void (^block)(); //定义block语句块,存储到了block变量中 block = ^void() { NSLog(@"I am block"); }; //执行 block(); //实例 实现计算两数之和block //int myAdd(int x,int y); int (^myAdd)(int x,int y) = ^int(int x,int y) { return x+y; }; int s = myAdd(10,20); NSLog(@"s = %d",s); //3.block捕获外部变量 // block使用block外面的变量的注意事项 //int num = 10; __block int val = 100; void(^block1)() = ^void() { //能使用和修改实例变量 _page = 1; //block中不能修改局部变量的值 //num++; //block中能修改 __block修饰的局部变量 val++; // 可能有警告,因为内存问题引起,注意 // _weak typeof(self) weakoff = self; // block外定义 // weakSelf.url = @"text"; self.url = @"text"; }; block1();
3.block在开发中应用(OC,UI,网络)
使用block实现排序
Dog *ahua = [[Dog alloc] init]; ahua.nickname = @"ahua"; ahua.age = 4; Dog *wangcai = [[Dog alloc] init]; wangcai.nickname = @"wangcai"; wangcai.age = 3; Dog *dahuang = [[Dog alloc] init]; dahuang.nickname = @"dahuang"; dahuang.age = 5; NSMutableArray *marr = [[NSMutableArray alloc] initWithArray:@[ahua,wangcai,dahuang]]; [marr sortUsingComparator:^NSComparisonResult(id obj1, id obj2) { Dog *aDog = obj1; Dog *bDog = obj2; // return aDog.age > bDog.age; return [aDog.nickname compare:bDog.nickname] < 0; }]; for(Dog *d in marr) { NSLog(@"name = %@ age = %d",d.nickname,d.age); }
使用block实现动画
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; label.text = @"我是大赢家"; label.backgroundColor = [UIColor redColor]; [self.view addSubview:label]; [UIView animateWithDuration:2 animations:^{ CGRect frame = label.frame; frame.origin.x += 200; label.frame = frame; } completion:^(BOOL finished) { NSLog(@"动画结束"); [UIView animateWithDuration:1 animations:^{ label.transform = CGAffineTransformMakeRotation(M_PI); CGRect frame = label.frame; frame.origin.x -= 200; label.frame = frame; } completion:^(BOOL finished) { }]; }];
使用block实现界面传值
若有两个界面A界面, B界面, A界面创建B界面, B界面值传递到A界面
A界面设置block
-(void)btnClick:(UIButton *)btn { SecondViewController *secVC = [[SecondViewController alloc] init]; //设置block [secVC setChangeVackgroundColor:^(NSString *color) { if([color isEqualToString:@"blue"]) { self.view.backgroundColor = [UIColor blueColor]; } }]; [self presentViewController:secVC animated:YES completion:nil]; }
B界面保存block
-(void)btnClick:(UIButton *)btn { //改变主界面的颜色 if(_action) { _action(@"blue"); } [self dismissViewControllerAnimated:YES completion:nil]; } -(void)setChangeVackgroundColor:(void (^)(NSString *))action { _action = action; }