Polymorphic copy: Difference between revisions

Line 251:
All objects inherit the <code>copy</code> method from <code>NSObject</code>, which performs copying. But they must implement the <code>copyWithZone:</code> method to actually specify how to copy. Calling <code>copy</code> on an object that does not implement <code>copyWithZone:</code> will result in an error.
 
Implementing copying can be done with the <code>NSCopyObject()</code> function for a simple byte-for-byte shallow copy of the object fields. Or you can do something more complicated like explicitly allocate a new object of a certain class (but then it won't really be polymorphic) and initialize it with your object's data. I am not really clear on the details of this.
 
<lang objc>
Line 267:
 
// or:
// T *copy = [[T allocWithZone:zone] init]; // call an appropriate constructor here
// // then copy data into it as appropriate here
// return [copy init]; // construct the new object appropriately here, and copy the data to it
// return copy;
}
@end
Line 295 ⟶ 296:
</lang>
 
AnalagouslyAnalogously, there is a <code>mutableCopy</code> method to get a mutable copy of the current object (e.g. if you have an NSArray object and you want an NSMutableArray with the same contents). In this case it would have to implement the <code>mutableCopyWithZone:</code> method to specify how to copy.
 
=={{header|OCaml}}==
Anonymous user