How do copy and mutableCopy apply to NSArray and NSMutableArray?

前端 未结 8 1764
时光取名叫无心
时光取名叫无心 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:37

    To state it simply,

    • copy returns an immutable (can't be modified) copy of the array,
    • mutableCopy returns a mutable (can be modified) copy of the array.

    Copy (in both cases) means that you get a new array "populated" with object references to the original array (i.e. the same (original) objects are referenced in the copies.

    If you add new objects to the mutableCopy, then they are unique to the mutableCopy. If you remove objects from the mutableCopy, they are removed from the original array.

    Think of the copy in both cases, as a snapshot in time of the original array at the time the copy was created.

    0 讨论(0)
  • 2020-11-27 11:41
    -(id)copy always returns a immutable one & -(id)mutableCopy always returns a mutable object,that's it.
    

    You have to know the return type of these copying stuff and while declaring the new object which one will be assigned the return value must be of immutable or mutable one, otherwise compiler will show you error.

    The object which has been copied can not be modified using the new one,they are totally two different objects now.

    0 讨论(0)
提交回复
热议问题