美文网首页
001-weak和assign的区别

001-weak和assign的区别

作者: 紫荆秋雪_文 | 来源:发表于2017-02-27 22:09 被阅读29次

    1、测试场景:点击屏幕的时候给屏幕添加一个红色的view

    2、测试weak

    #import "ViewController.h"
    
    @interface ViewController ()
    /** 控件使用weak */
    @property (nonatomic,weak) UIView *redView;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        UIView *redView = [[UIView alloc] init];
        redView.backgroundColor = [UIColor redColor];
        [self.view addSubview:redView];
        _redView = redView;
    }
    
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
        //设置frame
        _redView.frame = CGRectMake(100, 100, 100, 100);
    }
    
    @end
    
    • 小结:点击屏幕可以实现屏幕上添加一个红色的view
    #import "ViewController.h"
    
    @interface ViewController ()
    /** 控件使用weak */
    @property (nonatomic,weak) UIView *redView;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        UIView *redView = [[UIView alloc] init];
        redView.backgroundColor = [UIColor redColor];
        //[self.view addSubview:redView];
        _redView = redView;
    }
    
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
        //设置frame
        _redView.frame = CGRectMake(100, 100, 100, 100);
    }
    
    @end
    
    • 小结:当注释[self.view addSubview:redView];代码后,由于redView没有强应用,所以过了viewDidLoad方法以后,redView就会被释放了。此时的_redView也没有指向了应该是一个“野指针”,但是程序并不会崩溃。这是因为redView是由于weak修饰的原因(weak:__weak 弱指针,不会让引用计数器+1,如果指向的对象被销毁,指针会自动情况)

    3、测试assgin

    #import "ViewController.h"
    
    @interface ViewController ()
    @property (nonatomic,assign) UIView *redView;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        UIView *redView = [[UIView alloc] init];
        redView.backgroundColor = [UIColor redColor];
        //[self.view addSubview:redView];
        _redView = redView;
    }
    
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
        //设置frame
        _redView.frame = CGRectMake(100, 100, 100, 100);
    }
    
    @end
    
    
    • 小结:当点击屏幕时,程序会奔溃!!!
    • 奔溃的原因是因为redView现在是使用 assgin 修饰,assgin的特性如下:assgin: __unsafe_unretained修饰,不会让引用计数器+1,如果指向的对象被销毁了,指针是不会自动清空的。

    相关文章

      网友评论

          本文标题:001-weak和assign的区别

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