9

I guess this is solved by writing a @protocol.

But I'm hungry for knowledge. Is there some flag or other way to require subclasses to override specific methods and not call super? Like the opposite of NS_REQUIRES_SUPER / objc_requires_super?

hfossli
  • 22,616
  • 10
  • 116
  • 130
  • I have seen an NSAssert in the super class before which raises an exception if the superclass is called, might be one way of doing it. – sbarow Mar 10 '14 at 10:18
  • Not sure but you can use category to override (however this is not appreciated). Also using swizzling. – Anoop Vaidya Mar 10 '14 at 10:36
  • I think what you'd have to do is test the class of the instance (with `isMemberOfClass`, not `isKindOfClass`) and throw an assertion if the class is not the same as the method's class. – Hot Licks Mar 10 '14 at 11:47
  • @HotLicks and these tests could typically be done in `-init`? – hfossli Mar 10 '14 at 14:52
  • You'd do the test in the method that was supposed to be overridden. – Hot Licks Mar 10 '14 at 15:31
  • Well, then what's the difference between your suggestion and @Basheer_CAD 's suggestion? – hfossli Mar 10 '14 at 15:38
  • His suggestion is doing the assert(NO) inevitably, which is fine if the superclass never stands on its own. If the superclass is used on its own, however, you'd want the assertion to be conditional. – Hot Licks Mar 11 '14 at 11:36

3 Answers3

1

I do that in code not using any flags.
- I add assertion in the method of the super class that needs to be overridden in case this method is get called

Here I have a class that have a method fetchUserData that should be overridden by the child class

- (void)fetchUserData
{
    NSString *descrip = [NSString stringWithFormat:@"child implementation for method:%@ :  %@",NSStringFromSelector(_cmd),  NSStringFromClass([self class])
    NSAssert(NO, descrip);
}
Basheer_CAD
  • 4,908
  • 24
  • 36
1

There are some things here that should be useful.

Specifically subclassResponsibility:

EDIT: Good point in the comments - GNUStep != Foundation. In other words, the methods on the page I linked to should be used with caution. However, I've personally used subclassResponsibility: and it works.

shmim
  • 729
  • 9
  • 21
1

If I understand this right you're essentially asking how to make an abstract class... forcing subclasses to implement methods.

Check out : Creating an abstract class in Objective-C

In short, have the method throw an exception.

Community
  • 1
  • 1