One of my favorite interview questions for a programming position is "What is the difference between a class, an abstract class, and an interface?". You'd be surprised how many people can't answer that. Anyways, that's my intro to today's lesson, where we attempt to create an abstract class in Objective-C.
Hopefully by now you know that an interface is a type whose methods are devoid of implementation, and it cannot serve as an instantiated class on it's own; it's not actually a class. An abstract class can have methods devoid of implementation, but has at least one method that contains implementation. It also contains member variables.
Enough of the introduction, and let's get down to business. First off, you cannot create an abstract class in Objective-C; there is no abstract modifier. I recently had the need for an abstract class and an interface in a project I was working on, and I emulated an abstract class to the best of my ability. Here's what I came up with:
// MyObject.h
#import
@protocol IMyObject
-(void) myMethod;
@end
@interface MyObject : NSObject {
NSUInteger myID;
}
@property (
nonatomic) NSUInteger myID;
-(void) myMethod2;
@end
// MyObject
#import "MyObject.h"
@implementation MyObject
@synthesize myID;
- (id)init
{
[self doesNotRecognizeSelector:_cmd];
[self release];
return nil;
}
-(void) myMethod {
[self doesNotRecognizeSelector:_cmd];
}
-(void) myMethod2 {
//do stuff
}
@end
So, the above class header file contains a nested @protocol which declares a required method signature. You can declare optional methods inside the @protocol with a @optional declaration. Essentially, the protocol is defining my interface. Next I declare my actual class and implement my IMyObject interface, which "forces" me to implement myMethod. I quote the "forces" in that last because the compiler really just gives me a warning, not a full error.
I've also declared a member variable myID and a property for it in my "abstract" class implementation, along with myMethod2, which can contain actual implementation to inherit to the subclasses of this "abstract" class. It is key to note the [self doesNotRecognizeSelector:_cmd]; lines, where I am basically using that to declare the method as abstract. It will throw an error if you try to call the method on the base call. If you put that within your init method, the class will not be able to be instantiated on its own.