Polymorphic copy: Difference between revisions

m ({{omit from|AWK}})
Line 753:
 
=={{header|Objective-C}}==
All objects inherit the <code>copy</code> method from <code>NSObject</code>, which performs copying. But they must implement the <code>NSCopying</code> protocol (which involves implementing 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 cancould be done with the <code>NSCopyObject()</code> function for a simple byte-for-byte shallow copy of the object fields. However, thedue Appleto docsit saynot thatrespecting memory management of object pointer fields, this function is listed in the docs as "very difficult to use correctly", and "likely to be deprecated after Mac OS X 10.6". See [http://robnapier.net/blog/implementing-nscopying-439 this article] for reasons why it this function is problematic.
 
AlternatelyGenerally, youto canimplement copying, if your parent class does not implement <code>NSCopying</code>, you explicitly allocate a new object (using the class object <code>[self class]</code> instead of hard-coding the name of a particular class, in order to be polymorphic), and initialize it with your object's data. If your parent class already implements <code>NSCopying</code>, and you wish to customize the copying of your class's fields, then you should get a copy from your parent object's <code>copyWithZone:</code> method, and then perform custom initialization on the copy.
 
<lang objc>@interface T : NSObject
Line 769:
}
- (id)copyWithZone:(NSZone *)zone {
// T *copy = [[[self class] allocWithZone:zone] init]; // call an appropriate constructor here
return NSCopyObject(self, 0, zone); // polymorphically copy self
// // then copy data into it as appropriate here
 
// // make sure to use "[[self class] alloc..." and
// or:
// // not "[T alloc..." to make it polymorphic
// T *copy = [[[self class] allocWithZone:zone] init]; // call an appropriate constructor here
// return copy;
// // then copy data into it as appropriate here
// // make sure to use "[[self class] alloc..." and
// // not "[T alloc..." to make it polymorphic
// return copy;
}
@end
Line 802 ⟶ 799:
}</lang>
 
Analogously, 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>NSMutableCopying</code> protocol (which involves implementing the <code>mutableCopyWithZone:</code> method) to specify how to copy.
 
=={{header|OCaml}}==
Anonymous user