Apress-Beginning iOS 7 Development CHAPTER 9

本文深入探讨了在Objective-C中使用NSArray时,选择使用copy还是strong关键字的重要性,解释了它们的区别及如何避免数据不一致的问题。

Note You may notice that the familyNames property is declared using the copy keyword instead ofstrong. What’s up with that? Why should we be copying arrays willy-nilly? The reason is the potential existence of mutable arrays.

Imagine if we had declared the property using strong, and an outside piece of code passed in an instance of NSMutableArray to set the value of the familyNames property. If that original caller later decides to change the contents of that array, the BIDRootViewController instance will end up in an inconsistent state, where the contents of familyNames is no longer in sync with what’s on the screen! Using copyeliminates that risk, since calling copy on any NSArray (including any mutable subclasses) always gives
us an immutable copy. Also, we don’t need to worry about the performance impact too much. As it turns out, sending
copy to any immutable object doesn’t actually copy the object. Instead, it returns the same object after increasing its reference count. In effect, calling copy on an immutable object is the same as callingretain, which is what ARC might do behind the scenes anytime you set a strong property. So, it works out just fine for everyone, since the object can never change.

This situation applies to all value classes where the base class is immutable, but mutable subclasses exist. These value classes include NSArray, NSDictionary, NSSet, NSString, NSData, and a few more.
Any time you want to hang onto an instance of one of these in a property, you should probably declare the property’s storage with
copy instead of strong to avoid any problems. 


from Apress-Beginning iOS 7 Development CHAPTER 9 page276


转载于:https://my.oschina.net/randy1986/blog/532431

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值