关于UIView(UIViewAnimationWithBlocks)一段有意思的代码

244 阅读2分钟

一个UIViewController 里面有个动画,在做循环动画(这里不讨论动画实现问题)。有兴趣的可以copy TestViewController去做实验,观察CPU占用。

代码如下:

@interface TestViewController ()
@property (nonatomic, strong) UIView *animationView;
@end

@implementation TestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.animationView];
    self.animationView.frame = CGRectMake(100, 100, 100, 100);
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor redColor];
    [button addTarget:self action:@selector(buttonPress) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    button.frame = CGRectMake(100, 222, 100, 44);
}

-(void)buttonPress{
    
    [self m1];
}


-(void)m1{
//    __weak typeof (self)weakSelf = self;
    NSLog(@"%@", NSStringFromSelector(_cmd));
    [UIView animateWithDuration:3 animations:^{
        self.animationView.alpha = 0.3;
    } completion:^(BOOL finished) {
        [self m2];
    }];
}

-(void)m2{
    NSLog(@"%@", NSStringFromSelector(_cmd));
    [UIView animateWithDuration:3 animations:^{
        self.animationView.alpha = 1;
    } completion:^(BOOL finished) {
        [self m1];
    }];
}

- (UIView *)animationView{
    if(!_animationView){
        _animationView = ({
            UIView * object = [[UIView alloc]init];
            object.backgroundColor = [UIColor redColor];
            object;
       });
    }
    return _animationView;
}

@end

当push进TestViewController 动画正常进行,无异常。 但是pop回去之后CPU占用率一直处于高负荷,项目中发现110+,写的测试代码是90+。 解决方法是:互相调用环节弱化一个self。

疑问1:3秒为何失效? 由于push进来互相调用是在动画3秒结束之后执行,不会有烧CPU的问题。但是pop,由于这个VC没有被释放,为何导致了3秒失效,但是不会崩溃,不管运行多久。控制台打印如下:

2020-07-10 17:15:42.628851+0800 Test[4446:883982] m1

2020-07-10 17:15:45.631535+0800 Test[4446:883982] m2

2020-07-10 17:15:48.634413+0800 Test[4446:883982] m1

2020-07-10 17:15:51.637173+0800 Test[4446:883982] m2

2020-07-10 17:15:54.639760+0800 Test[4446:883982] m1

2020-07-10 17:15:56.814943+0800 Test[4446:883982] m2(这里已pop回去了)

2020-07-10 17:15:56.816279+0800 Test[4446:883982] m1

2020-07-10 17:15:56.817411+0800 Test[4446:883982] m2

2020-07-10 17:15:56.818471+0800 Test[4446:883982] m1

2020-07-10 17:15:56.819416+0800 Test[4446:883982] m2

2020-07-10 17:15:56.820344+0800 Test[4446:883982] m1

2020-07-10 17:15:56.821094+0800 Test[4446:883982] m2

疑问2:为何不崩溃,CPU高?

如果把m1和m2方法改造成直接调用,程序会崩溃,这个应该好理解。但是动画3秒失效为何不会崩溃?

-(void)m1{
    
    [self m2];
}

-(void)m2{
    
    [self m1];
}