美文网首页iOS Developer
iOS-assgin与weak的根本区别

iOS-assgin与weak的根本区别

作者: 王技术 | 来源:发表于2017-04-18 09:34 被阅读0次

    本文介绍 iOS 中 assgin 与 weak 的区别

    • 首先是 weak 的使用:一般用于修饰控件:

    @interface ViewController ()
    @property (nonatomic, weak) UIView *redView;
    @end
    @implementation ViewController
    -(void)viewDidLoad {
        [super viewDidLoad];
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor redColor];
        [self.view addSubview:view];
        self.redView = view;
    }
    -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        _redView.frame = CGRectMake(50, 50, 200, 200);
    }
    

    当点击屏幕的时候走 touchesBegan 方法
    redView 有了 frame
    会显示在屏幕上
    说明在走完 viewDidLoad 的代码块时
    redView 没有被销毁
    因为 redView 被加入了控制器的 view
    由控制器对它进行了强引用

    -(void)viewDidLoad {
        [super viewDidLoad];
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor redColor];
        //[self.view addSubview:view];
        self.redView = view;
    }
    -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        _redView.frame = CGRectMake(50, 50, 200, 200);
    }
    

    现在把这句注掉:[self.view addSubview:view];
    继续点击屏幕
    由于 redView 没有被加入控制器的view
    也就没有人对它强引用
    过了 viewDidLoad 代码块后
    redView 被销毁了
    但是 touchesBega n中访问 redView 的时候
    程序没有报坏内存访问的错误

    原因就是因为weak做了些事情:

    如果指针指向的对象被销毁,那么 weak 会让这个指针也清空
    这时的 redView 是 __weak 修饰:


    weak.jpeg

    assgin 的使用:一般用于修饰基本数据类型

    为了演示 assgin 与 weak 的区别
    用 assgin 来修饰控件

    @interface ViewController ()
    @property (nonatomic, assign) UIView *redView;
    @end
    @implementation ViewController
    -(void)viewDidLoad {
        [super viewDidLoad];
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor redColor];
        //[self.view addSubview:view];
        self.redView = view;
    }
    -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        _redView.frame = CGRectMake(50, 50, 200, 200);
    }
    

    这里用 assgin 修饰的控件 redView 也没有加入到控制器 view 中
    也就没有人对 redView 进行强引用
    当点击屏幕走 touchesBegan 方法时
    就会报坏内存访问错误
    因为 assign 并没有把指针清空
    这时的 redView 是 __unsafe_unretained 修饰:


    assgin.jpeg

    总结:

    • weak:

    __weak 修饰
    弱指针
    不会让引用计数器 +1
    如果指向对象被销毁,指针会自动清空
    ARC才有

    • assgin:

    __unsafe_unretained 修饰
    不会让引用计数器 +1
    如果指向对象被销毁,指针不会清空

    感谢阅读
    你的支持是我写作的唯一动力

    相关文章

      网友评论

        本文标题:iOS-assgin与weak的根本区别

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