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));

     
  • 相关阅读:
    在windows环境中使用varnish
    CENTOS 5.5 64位 编译安装 webbench 1.5网站压力测试工具
    CentOS设置时间
    Tomcat性能优化
    Squid 2.6 2.7 3.0 3.1 以及 varnish 2.1.5 性能对比测试
    Varnish加速网站图片显示
    保护你的Web服务器 iptables防火墙脚本全解读
    纯静态文件环境下的Nginx优化思路
    tomcat报 Context [] startup failed due toprevious errors
    siege工具安装
  • 原文地址:https://www.cnblogs.com/ganeveryday/p/4930729.html
Copyright © 2011-2022 走看看