ios开发 block语句块
1.block 理解为匿名函数
2.block变量的定义
//定义block变量,^表示定义block
//技巧:函数名左右加括号,在函数名前面在加^
void (^block)(); //定义block语句块,存储到了block变量中
block=^void ()
{
NSLog(@"I am block");
}; //执行
block();
3.带有参数和返回值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(,);
NSLog(@"s=%d",s);
4.block捕获外部外部变量(下面代码的_url和_page 为全局变量)
//block使用block外面的变量的注意事项
//int num=10;
__block int val=;
void (^b1)()=^void()
{
//能使用和修改实例变量
_page=;
//block中不能修改局部变量的值
//num++; //block中能修改__block修饰的局部变量
val++; //有可能有警告,因为内存问题引起,注意(用下面的方法)
//__weak typeof(self) weakSelf = self;//block外面定义
//weakSelf.url = @"text";
self.url = @"txt";
}; b1();
5.oc 中应用
(1)NSMutableArray排序(另外定义一个类Dog继承于NSObject)
Dog *huahua=[[Dog alloc] init];
huahua.nickName=@"huahua";
huahua.age=; Dog *miao=[[Dog alloc] init];
miao.nickName=@"miaomiao";
miao.age=; Dog *dahuang=[[Dog alloc] init];
dahuang.nickName=@"dahuang";
dahuang.age=; NSMutableArray *marr=[[NSMutableArray alloc] initWithArray:@[huahua,miao,dahuang]];
//marr sortUsingSelector:<#(SEL)#>//(以前用的方法)
[marr sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
Dog *aDog=obj1;
Dog *bDog=obj2;
//return aDog.age>bDog.age;//按年龄升序排序
//按名字排序
return [aDog.nickName compare:bDog.nickName]<;
}]; for(Dog *d in marr)
{
NSLog(@"name = %@ , age = %d",d.nickName,d.age);
}
(2)UIView动画
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(, , , )];
label.text=@"我是label";
label.backgroundColor=[UIColor redColor];
[self.view addSubview:label]; //向下移动200
[UIView animateWithDuration: animations:^{
CGRect frame=label.frame;
frame.origin.y+=;
label.frame=frame;
} completion:^(BOOL finished) {
NSLog(@"动画结束");
label.transform=CGAffineTransformMakeRotation(M_PI);
[UIView animateWithDuration: animations:^{
CGRect frame=label.frame;
frame.origin.y-=;
label.frame=frame;
} completion:^(BOOL finished) { }];
}];
6.block实现界面反向传值
创建一个视图类SecondViewController继承于UIViewController
(1)在SecondViewController.h文件定义下面的方法
//为了给第二个界面传入block
-(void)setChangeBackgroundColor:(void (^)(NSString *color)) action;
(2)在SecondViewController.m文件实现下面的方法
-(void)btnClick
{
//改变主界面的颜色
if (_action) {
_action(@"blue");
} [self dismissViewControllerAnimated:YES completion:nil];
}
(3)在UIViewController视图实现下面方法
-(void)btnClick
{
SecondViewController *svc=[[SecondViewController alloc] init]; //设置block
[svc setChangeBackgroundColor:^(NSString *color) {
if ([color isEqualToString:@"blue"]) {
self.view.backgroundColor=[UIColor blueColor];
}
}]; [self presentViewController:svc animated:YES completion:nil];
}
经过上面三个步骤就可用block实现界面反向传值(这里传的是视图背景颜色)