Created
September 18, 2013 04:17
-
-
Save timothyekl/6604488 to your computer and use it in GitHub Desktop.
Abstract superclass initializers in Objective-C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface Parent : NSObject | |
@end | |
@implementation Parent | |
- (id)init; | |
{ | |
if (!(self = [super init])) | |
return nil; | |
if ([self class] == [Parent class]) { | |
[NSException raise:@"Instantiate a subclass!" format:nil]; | |
return nil; | |
} | |
return self; | |
} | |
- (NSString *)description; | |
{ | |
return [NSString stringWithFormat:@"<%@:%p>", NSStringFromClass([self class]), self]; | |
} | |
@end | |
@interface Child : Parent | |
@end | |
@implementation Child | |
- (id)init; | |
{ | |
if (!(self = [super init])) | |
return nil; | |
return self; | |
} | |
@end | |
int main(int argc, char *argv[]) { | |
@autoreleasepool { | |
Child *child = [[Child alloc] init]; | |
NSLog(@"%@", [child description]); | |
Parent *parent = [[Parent alloc] init]; | |
NSLog(@"%@", [parent description]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment