UIScrollView导致的崩溃

作者: bigParis | 来源:发表于2016-08-30 12:59 被阅读1599次

    在使用delegate时候, 尤其是自定义delegate的时候, 都会自觉不自觉的加上weak属性, 系统的delegate也是这样写的, @property(nullable,nonatomic,weak) id<UIScrollViewDelegate>, 当然, 这样写的一个主要原因是为了防止循环引用, 但是在iOS8.x的系统上delegate并不是weak属性, 而是__unsafe_unretained.

    先来说下__unsafe_unretained和weak的区别

    先上段代码

       __unsafe_unretained id obj0 = nil;
        {
            id obj1 = [[NSObject alloc] init];
            obj0 = obj1;
            
            NSLog(@"obj1: %@", obj1);
        }
        
        NSLog(@"obj0: %@", obj0);
    
        __weak id obj0 = nil;
        {
            id obj1 = [[NSObject alloc] init];
            obj0 = obj1;
            
            NSLog(@"obj1: %@", obj1);
        }
        
        NSLog(@"obj0: %@", obj0);
    

    __unsafe_unretained从名字上就可以看出来, 不安全, 赋值的时候引用计数不增加, 也就是obj0被赋值为obj1的地址, 但是出了obj1的作用域, obj1被释放了, 而obj0并不释放, 而是依旧持有, 这样就会造成不安全!

    而使用weak的时候, 出了obj1的作用域, obj1被释放, obj0引用计数为0被释放, 随即会把obj0置为nil.

    崩溃堆栈&&场景重现

    0  libobjc.A.dylib!objc_msgSend + 0x10
    1  UIKit!-[UIScrollView(UIScrollViewInternal) _delegateScrollViewAnimationEnded] + 0x40
    2  UIKit!-[UIScrollView(UIScrollViewInternal) _scrollViewAnimationEnded:finished:] + 0xcc
    3  UIKit!-[UIAnimator stopAnimation:] + 0x1f4
    4  UIKit!-[UIAnimator(Static) _advanceAnimationsOfType:withTimestamp:] + 0x14c
    5  QuartzCore!CA::Display::DisplayLinkItem::dispatch() + 0x1c
    6  QuartzCore!CA::Display::DisplayLink::dispatch_items(unsigned long long, unsigned long long, unsigned long long) + 0x140
    7  IOKit!IODispatchCalloutFromCFMessage + 0x174
    8  CoreFoundation!__CFMachPortPerform + 0xb0
    9  CoreFoundation!__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 0x34
    

    大体上意思就是, 在scrollView滑动结束的时候, 会继续使用delegate, 而此时的delegate已经释放了, 在iOS9+系统上, 是没有问题的, 因为delegate是weak的, 释放了立即置空, 不存在安全隐患, 而iOS9-, 则不行, 因为是__unsafe_unretained的, 所以, 释放了, 但不置空, 这就造成了野指针崩溃.

    重现代码

    #import "ScrollViewController.h"
    
    @interface ScrollViewController ()<UIScrollViewDelegate>
    
    @property (nonatomic, weak) UIScrollView *scrollView;
    @property (nonatomic, weak) UIView *leftView;
    @property (nonatomic, weak) UIView *centerView;
    @property (nonatomic, weak) UIView *rightView;
    @property (nonatomic, assign) NSInteger currentPage;
    @end
    
    @implementation ScrollViewController
    
    - (void)dealloc {
        NSLog(@"dealloc");
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        UIScrollView *scrollView = [[UIScrollView alloc] init];
        scrollView.delegate = self;
        [self.view addSubview:scrollView];
        
        UIView *leftView = [[UIView alloc] init];
        leftView.backgroundColor = UIColor.redColor;
        [scrollView addSubview:leftView];
        
        UIView *centerView = [[UIView alloc] init];
        centerView.backgroundColor = UIColor.blueColor;
        [scrollView addSubview:centerView];
        
        UIView *rightView = [[UIView alloc] init];
        rightView.backgroundColor = UIColor.greenColor;
        [scrollView addSubview:rightView];
        
        self.scrollView = scrollView;
        self.leftView = leftView;
        self.centerView = centerView;
        self.rightView = rightView;
        
        self.currentPage = 1;
    }
    
    - (void)viewDidLayoutSubviews {
        CGFloat W = self.view.frame.size.width;
        CGFloat H = self.view.frame.size.height;
        
        self.scrollView.frame = self.view.bounds;
        self.scrollView.contentSize = CGSizeMake(3*W, H);
        self.leftView.frame = CGRectMake(0, 0, W, H);
        self.centerView.frame = CGRectMake(W, 0, W, H);
        self.rightView.frame = CGRectMake(2*W, 0, W, H);
        
        [super viewDidLayoutSubviews];
    }
    
    #pragma mark - UIScrollViewDelegate
    - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
        NSLog(@"scrollViewWillBeginDragging");
        [self.navigationController popViewControllerAnimated:NO];
    }
    
    - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity
                  targetContentOffset:(inout CGPoint *)targetContentOffset  {
        NSLog(@"scrollViewWillEndDragging");
        float width = scrollView.bounds.size.width;
        CGFloat scrolledOffset = targetContentOffset->x - width * self.currentPage;
        
        if (scrolledOffset > 0 && scrolledOffset >= width / 2) {
            self.currentPage = self.currentPage + 1;
            [self.scrollView setContentOffset:CGPointMake(self.scrollView.bounds.size.width * self.currentPage, 0) animated:YES];
        } else if (scrolledOffset < 0 && fabs(scrolledOffset) >= width / 2) {
            self.currentPage = self.currentPage - 1;
            [self.scrollView setContentOffset:CGPointMake(self.scrollView.bounds.size.width * self.currentPage, 0) animated:YES];
        }
        
    }
    
    @end
    

    好的, 在scrollView开始滑动的时候就释放调当前的ViewController, 这时候由于系统持有scrollView在做动画, 并没有立即释放, 当动画结束后, 系统释放scrollView, 然后来到dealloc, self被释放, 但是问题的关键是这句代码

    [self.scrollView setContentOffset:CGPointMake(self.scrollView.bounds.size.width * self.currentPage, 0) animated:YES];
    

    这里scrollview会在整个做动画scrollViewWillBeginDragging, scrollViewWillEndDragging, scrollViewDidEndDragging等, 被系统强引用, 所以这里都是没问题的, 不会崩溃, 但是在里面再去做animated动画, 就很危险了, 因为这时候self即将被释放, 到时候, delegate将变成野指针, 所以当animated动画结束的时候会造成崩溃(可能animated结束的时候系统又用delegate去做了什么事情).
    因为控制台打出的日志显示

    [ScrollViewController respondsToSelector:]: message sent to deallocated instance 0x7ff8324d6900

    经调查发现0x7ff8324d6900这个地址正是delegate原来的地址.

    解决办法

    那么这样一来, 我们是不是可以通过把delegate置空来避免崩溃呢'?
    可以:

    _scrollView.delegate = nil;

    这也是最简单的解决办法, _scrollView.delegate置空后面拿delegate干事儿就安全了, 还有一个办法, hook dealloc, 通常我们再将scrollView后不会去考虑scrollView.delegate的安全性问题, 因为都会觉得, 随着scrollview的置空delegate也将被置空, 然而并不是(iOS9-不是)!

    有关hook这里就不多表了, 懂的自然懂, 不懂也不是一两句话就能说明白的, 直接上代码

    + (void)hookUIScrollViewSetDelegate
    {
        [MethodsHooker hookMethedClass:NSClassFromString(@"UIScrollView")
                               hookSEL:@selector(setDelegate:)
                           originalSEL:@selector(originalSetDelegate:)
                             myselfSEL:@selector(myselfSetDelegate:)];
    }
    
    - (void)myselfSetDelegate:(UIViewController *)delegate
    {
        if (delegate) {
            UIScrollView * __weak weak_self = (UIScrollView *)self;
            [delegate setDeallocCallback:^{
                weak_self.delegate = nil;
                
                if ([weak_self isKindOfClass:[UITableView class]]) {
                    ((UITableView *)weak_self).editing = NO;
                    ((UITableView *)weak_self).dataSource = nil;
                    ((UITableView *)weak_self).delegate = nil;
                    
                } else if ([weak_self isKindOfClass:[UICollectionView class]]) {
                    ((UICollectionView *)weak_self).dataSource = nil;
                    ((UICollectionView *)weak_self).delegate = nil;
                }
            }];
        }
        
        [self originalSetDelegate:delegate];
    }
    
    - (void)originalSetDelegate:(id)delegate
    {
        
    }
    
    .h
    #import <UIKit/UIKit.h>
    
    typedef void (^DeallocCallback)();
    
    @interface UIViewController (Dealloc)
    
    @property (nonatomic, copy) DeallocCallback deallocCallback;
    
    @end
    
    .m
    @implementation UIViewController (Dealloc)
    
    + (void)load
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            [self hookSelectorName:@"dealloc" withSelector:@selector(myUIViewControllerDealloc)];
        });
    }
    
    - (void)myUIViewControllerDealloc
    {
        DeallocCallback callback = [self deallocCallback];
        if (callback) {
            callback();
        }
        
        [self myUIViewControllerDealloc];
    }
    
    - (void)setDeallocCallback:(DeallocCallback)callback
    {
        objc_setAssociatedObject(self, _cmd, callback, OBJC_ASSOCIATION_COPY_NONATOMIC);
    }
    
    - (DeallocCallback)deallocCallback
    {
        return objc_getAssociatedObject(self, @selector(setDeallocCallback:));
    }
    @end
    

    这里在给scrollView设置delegate的时候, 同时为delegate的dealloc方法添加block. 为了执行到自己写的block, 我们还要hook dealloc, 这样执行dealloc会先执行我们的block中的代码, 这里会将delegate置空, 从而完成任务.

    相关文章

      网友评论

      • 取个名字怎么那么难啊:有一点说错了,__unsafe_unretained修饰的obj0并不是被强持有,只是对象dealloc没有自动动为nil,从而造成野指针
      • starfox寒流:setContentOffset会导致delegate调用 scrollViewDidEndScrollingAnimation 这个代理方法。
      • bigParis:delegate = nil, 也是可以setContentOffset的.
        wyman666666:delegate = nil 这句代码在哪里写?
      • starfox寒流:delegate 置为nil之后 setContentOffset是不就没有效果了??

      本文标题:UIScrollView导致的崩溃

      本文链接:https://www.haomeiwen.com/subject/znufettx.html