copy 和 mutableCopy 如何应用于 NSArray 和 NSMutableArray? [英] How do copy and mutableCopy apply to NSArray and NSMutableArray?
问题描述
copy
和 mutableCopy
在 NSArray
或 NSMutableArray
上使用时有什么区别?
What is the difference between copy
and mutableCopy
when used on either an NSArray
or an NSMutableArray
?
这是我的理解;正确吗?
This is my understanding; is it correct?
// ** NSArray **
NSArray *myArray_imu = [NSArray arrayWithObjects:@"abc", @"def", nil];
// No copy, increments retain count, result is immutable
NSArray *myArray_imuCopy = [myArray_imu copy];
// Copys object, result is mutable
NSArray *myArray_imuMuta = [myArray_imu mutableCopy];
// Both must be released later
<小时>
// ** NSMutableArray **
NSMutableArray *myArray_mut = [NSMutableArray arrayWithObjects:@"A", @"B", nil];
// Copys object, result is immutable
NSMutableArray *myArray_mutCopy = [myArray_mut copy];
// Copys object, result is mutable
NSMutableArray *myArray_mutMuta = [myArray_mut mutableCopy];
// Both must be released later
推荐答案
copy
和 mutableCopy
定义在不同的协议(NSCopying
和 NSMutableCopying
,分别)和 NSArray
符合两者.mutableCopy
是为 NSArray
(不仅仅是 NSMutableArray
)定义的,它允许你制作一个原始不可变数组的可变副本:
copy
and mutableCopy
are defined in different protocols (NSCopying
and NSMutableCopying
, respectively), and NSArray
conforms to both. mutableCopy
is defined for NSArray
(not just NSMutableArray
) and allows you to make a mutable copy of an originally immutable array:
// create an immutable array
NSArray *arr = [NSArray arrayWithObjects: @"one", @"two", @"three", nil ];
// create a mutable copy, and mutate it
NSMutableArray *mut = [arr mutableCopy];
[mut removeObject: @"one"];
总结:
- 您可以依赖
mutableCopy
的结果是可变的,而不管原始类型如何.对于数组,结果应该是NSMutableArray
. - 你不能依赖于
copy
的结果是可变的!copy
NSMutableArray
可能返回一个NSMutableArray
,因为这是原始类,但是copycode>ing 任何任意
NSArray
实例都不会.
- you can depend on the result of
mutableCopy
to be mutable, regardless of the original type. In the case of arrays, the result should be anNSMutableArray
. - you cannot depend on the result of
copy
to be mutable!copy
ing anNSMutableArray
may return anNSMutableArray
, since that's the original class, butcopy
ing any arbitraryNSArray
instance would not.
根据 Mark Bessey 的回答重新阅读您的原始代码.当您创建阵列的副本时,当然您仍然可以修改原始阵列,无论您对副本进行什么操作.copy
vs mutableCopy
影响新数组是否可变.
re-read your original code in light of Mark Bessey's answer. When you create a copy of your array, of course you can still modify the original regardless of what you do with the copy. copy
vs mutableCopy
affects whether the new array is mutable.
编辑 2: 修正了我的(错误)假设,即 NSMutableArray -copy
将返回一个 NSMutableArray
.
Edit 2: Fixed my (false) assumption that NSMutableArray -copy
would return an NSMutableArray
.
这篇关于copy 和 mutableCopy 如何应用于 NSArray 和 NSMutableArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!