有什么区别copy
and mutableCopy
当用于任一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
copy
and mutableCopy
在不同的协议中定义(NSCopying
and NSMutableCopying
,分别),和NSArray
两者都符合。mutableCopy
定义为NSArray
(不只是NSMutableArray
)并允许您制作原始不可变数组的可变副本:
// 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
.
- you cannot取决于结果
copy
是可变的!copy
ing an NSMutableArray
may返回一个NSMutableArray
,因为那是原来的类,但是copy
任意任意NSArray
实例不会。
Edit:根据马克·贝西的回答重新阅读你的原始代码。当您创建数组的副本时,当然您仍然可以修改原始数组,无论您如何处理该副本。copy
vs mutableCopy
影响是否新数组是可变的。
Edit 2:修正了我的(错误的)假设NSMutableArray -copy
会返回一个NSMutableArray
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)