How do copy and mutableCopy apply to NSArray and NSMutableArray?

前端 未结 8 1797
时光取名叫无心
时光取名叫无心 2020-11-27 10:55

What is the difference between copy and mutableCopy when used on either an NSArray or an NSMutableArray?

This is

8条回答
  •  旧巷少年郎
    2020-11-27 11:19

    I think you must have misinterpreted how copy and mutableCopy work. In your first example, myArray_COPY is an immutable copy of myArray. Having made the copy, you can manipulate the contents of the original myArray, and not affect the contents of myArray_COPY.

    In the second example, you create a mutable copy of myArray, which means that you can modify either copy of the array, without affecting the other.

    If I change the first example to try to insert/remove objects from myArray_COPY, it fails, just as you'd expect.


    Perhaps thinking about a typical use-case would help. It's often the case that you might write a method that takes an NSArray * parameter, and basically stores it for later use. You could do this this way:

    - (void) doStuffLaterWith: (NSArray *) objects {
      myObjects=[objects retain];
    }
    

    ...but then you have the problem that the method can be called with an NSMutableArray as the argument. The code that created the array may manipulate it between when the doStuffLaterWith: method is called, and when you later need to use the value. In a multi-threaded app, the contents of the array could even be changed while you're iterating over it, which can cause some interesting bugs.

    If you instead do this:

    - (void) doStuffLaterWith: (NSArray *) objects {
      myObjects=[objects copy];
    }
    

    ..then the copy creates a snapshot of the contents of the array at the time the method is called.

提交回复
热议问题