Frage

Consider the following:

// BaseClass is both NSCopyable and NSMutableCopyable
@interface MyClass : BaseClass {
    // a bunch of properties
}

// x is a MyClass* local variable in a method
MyClass *a = [x copy];         // a is a strong reference to an immutable copy?
MyClass *b = [x mutableCopy];  // b is a strong reference to a mutable copy?

Questions:

  1. Can I make any changes to the iVars of a? If not, what happens if I try to make changes to any of the iVars? Will I get indeterminate behaviour, e.g., sometimes it works, sometimes it doesn't, memory corruption, or does compiler prohibit it altogether?

  2. Can I make any changes to iVars of b?

War es hilfreich?

Lösung

Short answer

  1. Yes. No memory corruption, and no compile error if the iVar is accessible.
  2. Same as 1.

Long answer

Mutable and immutable copy is one of the core concepts found in the Apple's Foundation classes, such as NSString or NSArray. As stated in NSCopying protocol, the class that has implement "immutable vs mutable" concept must return immutable object for copyWithZone:.

However the immutability of the object is not enforced by the compiler or memory protection, but the class designer must design the class to make it return immutable object upon receiving copy message.

In your case, the common way to implement such thing is to make MyClass immutable, and subclass to MyMutableClass and make it mutable. Your call site should look like:

MyClass *a = [x copy];         
MyMutableClass *b = [x mutableCopy]; 

Note that implement mutable/immutable is sometimes quite tedious, so make sure you have enough reason to implement such feature.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top