• 【整理】Object-C中的属性(Property)的Setter:assign,copy,retain,weak,strong之间的区别和联系


    iOS编程过程中,经常看到一些属性前面有些修饰符,比如copy,retain等。

    这些关键字,是Object-C语言中,对于Property的setter。

    Mac官网:

    The Objective-C Programming Language – Declared Properties – Setter Semantics

    中的解释是:

    Setter Semantics

    These attributes specify the semantics of a set accessor. They are mutually exclusive.

    strong

    Specifies that there is a strong (owning) relationship to the destination object.

    weak

    Specifies that there is a weak (non-owning) relationship to the destination object.

    If the destination object is deallocated, the property value is automatically set to nil.

    (Weak properties are not supported on OS X v10.6 and iOS 4; use assigninstead.)

    copy

    Specifies that a copy of the object should be used for assignment.

    The previous value is sent a release message.

    The copy is made by invoking the copy method. This attribute is valid only for object types, which must implement the NSCopying protocol.

    assign

    Specifies that the setter uses simple assignment. This attribute is the default.

    You use this attribute for scalar types such as NSInteger and CGRect.

    retain

    Specifies that retain should be invoked on the object upon assignment.

    The previous value is sent a release message.

    In OS X v10.6 and later, you can use the __attribute__ keyword to specify that a Core Foundation property should be treated like an Objective-C object for memory management:

    @property(retain) __attribute__((NSObject)) CFDictionaryRef myDictionary;

    即使看完解释,其实也很难理解具体的含义。

    后来是看了很多人的总结,,再经过一些实际编程的折腾,尤其是:

    【已解决】iOS程序出现警告:ARC Semantic Issue,Assigning retained object to unsafe property;object will be released after assignment,之后程序运行出错:Thread 1: EXC_BAD_ACCESS(code=1,address=0xe0000010)

    才稍微有所理解的。

    整理如下:

    想要理解这几个setter的含义,必须先对Object-C中的ARC有所了解。

    关于ARC,简单说几句就是,编译器自动帮你实现了引用技术,不用再麻烦你去写retain,release等词去操心引用技术的事情了。

    关于ARC更详细的解释,可参考:

    【总结】iOS的自动引用计数(ARC,Automatic Reference Counting)

    strong和weak

    自从有了ARC,就可以使用weak或strong来说明属性是弱引用还是强引用;

    assign,retain和copy

    没有ARC之前,都是使用assign,retain,copy来修饰属性的。

    assign,主要用于数值类变量,即标量,直接赋值即可,不涉及引用计数的变化(标量值,也没有引用技术可以供管理);

    copy,是拷贝一份新的对象,引用计数重置为1,释放旧的对象;

    retain,是对于原对象,引用计数加1,不会释放旧的对象;

    如果一件事情你觉得难的完不成,你可以把它分为若干步,并不断寻找合适的方法。最后你发现你会是个超人。不要给自己找麻烦,但遇到麻烦绝不怕,更不要退缩。 电工查找电路不通点的最快方法是:分段诊断排除,快速定位。你有什么启示吗? 求知若饥,虚心若愚。 当你对一个事情掌控不足的时候,你需要做的就是“梳理”,并制定相应的规章制度,并使资源各司其职。
  • 相关阅读:
    linux学习之centos(四):git的安装
    MongoDB学习
    linux学习之centos(三):mysql数据库的安装和配置
    面经中高频知识点归纳(三)
    各编程语言的内存分配方式
    carson常用linux命令整理
    在 Linux 虚拟机中手动安装或升级 VMware Tools
    Fidder 网络抓包调试工具
    面经中高频知识点归纳(二)
    java集合类
  • 原文地址:https://www.cnblogs.com/wvqusrtg/p/4261638.html
Copyright © 2020-2023  润新知