Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an abstract class in Objective-C

I'm originally a Java programmer who now works with Objective-C. I'd like to create an abstract class, but that doesn't appear to be possible in Objective-C. Is this possible?

If not, how close to an abstract class can I get in Objective-C?

like image 670
Jonathan Arbogast Avatar asked Jun 23 '09 18:06

Jonathan Arbogast


2 Answers

No, there is no way to create an abstract class in Objective-C.

You can mock an abstract class - by making the methods/ selectors call doesNotRecognizeSelector: and therefore raise an exception making the class unusable.

For example:

- (id)someMethod:(SomeObject*)blah {      [self doesNotRecognizeSelector:_cmd];      return nil; } 

You can also do this for init.

like image 24
Grouchal Avatar answered Sep 19 '22 22:09

Grouchal


Typically, Objective-C class are abstract by convention only—if the author documents a class as abstract, just don't use it without subclassing it. There is no compile-time enforcement that prevents instantiation of an abstract class, however. In fact, there is nothing to stop a user from providing implementations of abstract methods via a category (i.e. at runtime). You can force a user to at least override certain methods by raising an exception in those methods implementation in your abstract class:

[NSException raise:NSInternalInconsistencyException              format:@"You must override %@ in a subclass", NSStringFromSelector(_cmd)]; 

If your method returns a value, it's a bit easier to use

@throw [NSException exceptionWithName:NSInternalInconsistencyException                                reason:[NSString stringWithFormat:@"You must override %@ in a subclass", NSStringFromSelector(_cmd)]                              userInfo:nil]; 

as then you don't need to add a return statement from the method.

If the abstract class is really an interface (i.e. has no concrete method implementations), using an Objective-C protocol is the more appropriate option.

like image 190
Barry Wark Avatar answered Sep 23 '22 22:09

Barry Wark