How to block a superclass method that needs to be called in a subclass

I am extending the functionality of a class from a subclass, and I am doing some dirty things that make superclass methods dangerous (the application will hang in a loop) in the context of the subclass. I know that this is not a great idea, but I am going to use low-hanging fruits, and now it will save me. Oh, it's a dirty job, but someone has to do it.

On the bottom line, I need to either block this method from the outside, or throw an exception when it is called directly in the superclass. (But I still use it from a subclass, except with caution).

What would be the best way to do this?

UPDATE ---

So this is what I went for. I do not answer my own questions, as Boaz's answer mentions several valid ways to do this, this is exactly what suits me. In a subclass, I tried the method as follows:

- (int)dangerousMethod { [NSException raise:@"Danger!" format:@"Do not call send this method directly to this subclass"]; return nil; } 

I mark this as an answer, but obviously this does not mean that it is closed, further suggestions are welcome.

+4
source share
5 answers

Just re-implement the unsafe method in your subclass and do nothing or throw an exception or reimplement it as safe until the new implementation calls the unsafe superclass method.

For the C ++ team here: Objective-C does not allow you to mark methods as private. You can use your category system to split the interface into separate files (thus hiding 'private'), but all methods in the class are public.

+5
source

You can override any methods that you want to block in your subclass .h . You can make dangerousMethod unavailable by placing the following in the .h file.

 - (int)dangerousMethod __attribute__((unavailable("message"))); 

This will make the dangerousMethod method inaccessible to anyone using your subclass.

To prevent other code from using the superclass version, you can restrict this method by placing it in a .m file.

 - (int)dangerousMethod { return nil; } 
+6
source

note: I'm an ObjC / Cocoa newbie:

 @implementation MyClass -(void)myMethod:(NSString *)txt{ if([self class] != [MyClass class]) return; NSLog(@"Hello"); } @end 

Peter

+1
source

This article explains how to create private variables in Objective-C . They are not really private, but from what I read, the compiler will raise a warning if you try to call them from a subclass.

+1
source

If you create methods in your superclass as "private", then the subclass cannot call them. I am not familiar with Objective-C, but every other object-oriented language I have seen has the qualifier "private".

-3
source

All Articles