copy和mutableCopy如何应用于NSArray和NSMutableArray? [英] How do copy and mutableCopy apply to NSArray and NSMutableArray?
问题描述
在 NSArray <上使用
copy
和 mutableCopy
有什么区别? / code>或 NSMutableArray
?
What is the difference between copy
and mutableCopy
when used on either an NSArray
or an NSMutableArray
?
这是我的理解;
// ** 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
推荐答案
副本
和 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
。 - 您不能取决于结果
副本
可变!副本
放入NSMutableArray
可能返回NSMutableArray
,因为那是原始类,但是副本
不能使用任何任意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
与 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屋!