Skip to content

Instantly share code, notes, and snippets.

@atnan
Created August 8, 2010 04:04
Show Gist options
  • Save atnan/513571 to your computer and use it in GitHub Desktop.
Save atnan/513571 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
/*
$ gcc -x objective-c -Wno-import -lobjc -framework Foundation subclassing.m
$ ./a.out
-[FooThatCallsSelf initWithBar:]
-[SubFooThatCallsSelf init]
-[FooThatCallsSuper initWithBar:]
*/
@interface FooThatCallsSelf : NSObject
@end
@implementation FooThatCallsSelf
- (id)initWithBar:(NSString *)bar {
printf("-[FooThatCallsSelf initWithBar:]\n");
return [self init];
}
@end
@interface SubFooThatCallsSelf : FooThatCallsSelf
@end
@implementation SubFooThatCallsSelf
- (id)init {
printf("-[SubFooThatCallsSelf init]\n");
return [super init];
}
@end
@interface FooThatCallsSuper : NSObject
@end
@implementation FooThatCallsSuper
- (id)initWithBar:(NSString *)bar {
printf("-[FooThatCallsSuper initWithBar:]\n");
return [super init]; // this is incorrect
}
@end
@interface SubFooThatCallsSuper : FooThatCallsSuper
@end
@implementation SubFooThatCallsSuper
- (id)init {
printf("-[SubFooThatCallsSuper init]\n"); // will not be printed
return [super init];
}
@end
int main(void) {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
[[[SubFooThatCallsSelf alloc] initWithBar:@"BAR!"] autorelease];
[[[SubFooThatCallsSuper alloc] initWithBar:@"BAR!"] autorelease];
[pool release];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment