zoukankan      html  css  js  c++  java
  • 请解释以下keywords的区别: assign vs weak, __block vs __weak

    assign vs weak, __block vs __weak

    字数364 阅读74 评论0

    在objective-c中,类中的全局变量经常使用如下的方式申明。

    @property(nonatomic(1),strong(2))UIImageView *imageView;

    其中的1,2处是对此变量的一些属性申明。有以下几种
    strong
    weak
    assign
    strong 和 weak 是在arc后引入的关键字,strong类似于retain,引用时候会引用计算+1,weak相反,不会改变引用计数。
    weak和assign都是引用计算不变,两个的差别在于,weak用于object type,就是指针类型,而assign用于简单的数据类型,如int BOOL 等。
    assign看起来跟weak一样,其实不能混用的,assign的变量在释放后并不设置为nil(和weak不同),当你再去引用时候就会发生错误,崩溃,EXC_BAD_ACCESS.

    Has an assign attribute, AND Has been deallocated. Thus when you attempt to call the respondsToSelector method on delegate, you get a EXC_BAD_ACCESS. This is because objects that use the assign property will not be set to nil when they are deallocated. (Hence why doing a !self.delegate before the respondsToSelector does not prevent the responseToSelector from being called on a deallocated object, and still crashes your code) The solution is to use the weak attribute, because when the object deallocates, the pointer WILL be set the nil . So when your code calls respondsToSelector on a nil, Objective C will ignore the call, and not crash.

    block 不能修改局部变量,如果需要修改需要加上block.
    block 会对对象强引用,引起retain-cycle,需要使用
    weak

    __weak __typeof(&*self)weakSelf =self;

    在block种使用weakSelf可避免这种强引用。
    (两个指针,指向同一块地址(self));

     
  • 相关阅读:
    数学建模课程常用英语词汇(专业术语)
    MATLAB简易画图
    MATLAB与C语言对比实例:随机数生成
    C语言 投票系统:给定候选人,从键盘输入候选人的名字,统计票数,并输出最终获胜者
    C语言 一个数学问题:求s=(a^m)!+(b^n)!
    C语言 矩阵的转置及矩阵的乘法
    iOS_数据存取(二)
    iOS_数据存取(一)
    iOS_SDWebImage框架分析
    iOS_AFNetWorking框架分析
  • 原文地址:https://www.cnblogs.com/ganeveryday/p/4930729.html
Copyright © 2011-2022 走看看