Objective-C中的Strong、Copy与MutableCopy

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

能够先参考这篇文章http://www.cnblogs.com/lihaiyin/p/4647426.html面试

 

问题一:到底用Copy仍是Strongthis

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

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

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

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

 

所以,咱们的代码中通常都会  把不可变对象写成Copy  把可变对象写成Strongblog

 

问题二:源码中的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生成了新的对象,只是为了生成“不可变”的对象

相关文章
相关标签/搜索