02.7-Block
2018-11-26 本文已影响0人
weyan
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *redView;
@property (nonatomic, copy) void(^completionTask)();
@end
@implementation ViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// [UIView animateWithDuration:0.5 animations:^{
// self.redView.center = CGPointMake(300, 400);
// }completion:^(BOOL finished) {
//
// }];
// [UIView beginAnimations:nil context:nil];
// [UIView setAnimationDuration:0.5];
// [UIView setAnimationDelegate:self];
// [UIView setAnimationDidStopSelector:@selector(stop)];
//
// //动画执行代理
// self.redView.center = CGPointMake(300, 400);
// self.redView.bounds = CGRectMake(0, 0, 200, 200);
//
// [UIView commitAnimations];
//定义block
CGFloat duration = 0.5;
void (^task)() = ^{
self.redView.center = CGPointMake(300, 400);
self.redView.bounds = CGRectMake(0, 0, 200, 200);
};
[self myAnimateWithDuration:0.5 animations:^{
self.redView.center = CGPointMake(300, 400);
self.redView.bounds = CGRectMake(0, 0, 200, 200);
}completion:^{
NSLog(@"动画完成");
NSLog(@"动画完成");
NSLog(@"动画完成");
}];
}
- (void)myAnimateWithDuration:(CGFloat)duration animations:(void(^)())anim completion:(void(^)())completionTask{
self.completionTask = completionTask;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:duration];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(stop)];
//动画执行代理
anim();
[UIView commitAnimations];
}
//动画完成时调用
- (void)stop {
self.completionTask();
}
- (void)viewDidLoad {
[super viewDidLoad];
/***
Block的作用:
Block是一种数据类型,用来保存代码.
什么时候使用Block:当做参数进行传递时使用Block
当某一个方法当中, 某一部份代码不确定时, 此部分代码可以通过外界传入.(使用Blcok)
*/
int a = 10;
CGFloat b = 10.5;
// void(^blockName)() = ^(){
//
// NSLog(@"asdfasdf");
// NSLog(@"asdfasdf");
// NSLog(@"asdfasdf");
// NSLog(@"asdfasdf");
// NSLog(@"asdfasdf");
// NSLog(@"asdfasdf");
//
// };
//
// NSLog(@"%d",a);
// NSLog(@"%f",b);
//
// blockName();
// int(^sum)(int,int) = ^(int a, int b) {
// return a + b;
// };
//
// int res = sum(10,20);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
二、在开发中造成循环引用的情况:
**
1.当使用代理时
2.类与类之间的属性互相引用
3.block会对代码中的强指针进行强引用
4.当时有定时器时,注意可能会造成循环引用(消失时一定要关闭定时器)
**