面试过程中经常被问到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生成了新的对象,只是为了生成“不可变”的对象

最新文章

  1. 单核 -512M内存-2000并发正常使用
  2. slave IO流程之一:mysql登陆过程(mysql_real_connect)
  3. centos配置vpn服务器
  4. 【Python全栈笔记】01 [模块二] 14-15 Oct 运算符和字符串 4-1
  5. NOIP2015子串[序列DP]
  6. BZOJ-1012[JSOI2008]最大数maxnumber 线段树区间最值
  7. asp.net 安全性相关参考
  8. 定时组件quartz系列&lt;一&gt;模拟定时组件小程序
  9. Vs2008几个快捷键
  10. Strom实现单词统计代码
  11. android 09
  12. SxsTrace工具使用方法
  13. ActivityGroup相关--getLocalActivityManager() 以及intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)用法
  14. 第21章 策略模式(Strategy Pattern)
  15. solr5Ik分词2
  16. 基于YOLOv3和Qt5的车辆行人检测(C++版本)
  17. WebView内容自适应
  18. vi/vim键盘对应图
  19. windows 下mysql 重设root密码方法
  20. 20155334 2016-2017-2 《Java程序设计》第九周学习总结

热门文章

  1. Drools API的使用学习
  2. Go语言 字符串处理
  3. Eclipse导入到最新版Android Studio详解
  4. windows7 64位下环境搭建scrapy爬虫框架
  5. Windows - 性能监控之磁盘剩余空间大小警报
  6. 控制台游戏引擎CGE——贪吃蛇
  7. oracle EXP导出一张表时使用query参数指定where条件
  8. 树形DP
  9. Shell脚本基础
  10. js学习笔记