zoukankan      html  css  js  c++  java
  • Objective-C中的Strong、Copy与MutableCopy

    面试过程中经常被问到ARC中Strong、Copy的区别是什么。普通的回答是:一样。文艺(正确)的回答是:分情况(我擦!WQY#$&Y**%OWEUR)

    可以先参考这篇文章http://www.cnblogs.com/lihaiyin/p/4647426.html

    问题一:到底用Copy还是Strong

    1. 把不可变对象写成Copy:   如果把不可变对象赋值给此属性,内存中其实就是retain了一下。 如果把可变对象赋值给此属性,会生成新的不可变对象,避免值的变化

    2. 把不可变对象写成Strong: 如果把不可变对象赋值给此属性,内存中其实就是retain了一下。 如果把可变对象赋值给此属性,会导致赋值后的内容依然可变

    3. 把可变对象写成Strong:   如果把不可变对象赋值给此属性,调用此对象的addXX等增、删的方法时会崩溃。如果把可变对象赋值给此属性,内存中其实就是retain了一下。

    4. 把可变对象写成Copy:     无论是谁赋值给此属性,都会调用Copy生成不可变对象,都会在调用此对象的addXX等增、删的方法时会崩溃

    因此,我们的代码中一般都会  把不可变对象写成Copy  把可变对象写成Strong

    问题二:源码中的Copy方法为什么copyItem的参数是YES?

    /**
     * Returns a new copy of the receiver.<br />
     * The default abstract implementation of a copy is to use the
     * -initWithArray:copyItems: method with the flag set to YES.<br />
     * Immutable subclasses generally simply retain and return the receiver.
     */
    - (id) copyWithZone: (NSZone*)zone
    {
      NSArray    *copy = [NSArrayClass allocWithZone: zone];
    
      return [copy initWithArray: self copyItems: YES];
    }
    
    /**
     * Returns an NSMutableArray instance containing the same objects as
     * the receiver.<br />
     * The default implementation does this by calling the
     * -initWithArray:copyItems: method on a newly created object,
     * and passing it NO to tell it just to retain the items.
     */
    - (id) mutableCopyWithZone: (NSZone*)zone
    {
      NSMutableArray    *copy = [NSMutableArrayClass allocWithZone: zone];
    
      return [copy initWithArray: self copyItems: NO];
    }

    对比一下,发现initWithArray:copyItems方法的参数很怪。都知道,无论NSArray是copy还是mutableCopy,item都是retain的,不会copy,那为啥copyWithZone方法(copy方法调用时会调用此方法)的实现中,copyItem的参数是YES?

    -initWithArray:copyItems: method with the flag set to YES.<br />
     * Immutable subclasses generally simply retain and return the receiver

    想了很久,后来发现,答案就在注释中,不可变子类(NSString、NSArray、NSDictionary)一般只是简单的retain。。。对不可变对象调用copy只是retain,对可变对象调用copy会生成不可变对象,所以,为了使得新生成的NSArray“不可变”(元素本身也要不可变),只能使用copy,但这里的copy并非为item生成了新的对象,只是为了生成“不可变”的对象

  • 相关阅读:
    python之约束、加密及logging模块
    python之反射机制与callattr()、issubclass()、isinstance、type()相关
    python之面向对象初识
    python函数名的应用、闭包和迭代器
    python(动态传参、命名空间、函数嵌套、global和nonlocal关键字)
    python中函数的定义、返回值以及参数的简要介绍
    python文件操作
    python中set(集合),深浅拷贝以及一些补充知识点
    python中is与==的区别,编码和解码
    python数据类型:dict(字典)
  • 原文地址:https://www.cnblogs.com/lihaiyin/p/5241754.html
Copyright © 2011-2022 走看看