tasks a-s
This commit is contained in:
parent
47bf37c096
commit
b83f433714
12433 changed files with 156208 additions and 123 deletions
39
Task/Polymorphic-copy/Objective-C/polymorphic-copy.m
Normal file
39
Task/Polymorphic-copy/Objective-C/polymorphic-copy.m
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
@interface T : NSObject
|
||||
{ }
|
||||
- (void)identify;
|
||||
@end
|
||||
|
||||
@implementation T
|
||||
- (void)identify {
|
||||
NSLog(@"I am a genuine T");
|
||||
}
|
||||
- (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
|
||||
|
||||
@interface S : T
|
||||
{ }
|
||||
@end
|
||||
|
||||
@implementation S
|
||||
- (void)identify
|
||||
{
|
||||
NSLog(@"I am an S");
|
||||
}
|
||||
@end
|
||||
|
||||
int main()
|
||||
{
|
||||
T *original = [[S alloc] init];
|
||||
T *another = [original copy];
|
||||
[another identify]; // logs "I am an S"
|
||||
|
||||
[another release]; // like "alloc", the object returned by "copy" is "owned" by the caller, so we are responsible for releasing it
|
||||
[original release];
|
||||
return 0;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue