copy和mutableCopy如何应用于NSArray和NSMutableArray? [英] How do copy and mutableCopy apply to NSArray and NSMutableArray?

查看:136
本文介绍了copy和mutableCopy如何应用于NSArray和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 an NSMutableArray.
  • you cannot depend on the result of copy to be mutable! copying an NSMutableArray may return an NSMutableArray, since that's the original class, but copying any arbitrary NSArray 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆