【发布时间】:2011-01-01 09:51:35
【问题描述】:
在NSArray 或NSMutableArray 上使用copy 和mutableCopy 有什么区别?
这是我的理解;对吗?
// ** 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 分配给的变量 myArray_imuMuta 是 mutable,而不像您的注释所示的那样是不可变的。
-
谢谢,这是一个错误,我对 Xcode 感到困惑,说“警告 NSArray 可能无法响应添加 -addObject / -removeObjectAtIndex。我会将 myArray_imuMuta 更改为 NSMutableArray。
-
@JamesHarnett - 请停止以“ARC 兼容性”为名的编辑 - 请参阅 this meta post 了解原因。
标签: cocoa cocoa-touch nsmutablearray nsarray nscopying