Anonymous user
Polymorphic copy: Difference between revisions
→{{header|Objective-C}}
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
<lang objc>@interface T : NSObject
Line 769:
}
- (id)copyWithZone:(NSZone *)zone {
▲ // T *copy = [[[self class] allocWithZone:zone] init]; // call an appropriate constructor here
▲ // // 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}}==
|