how to block a superclass method to be called to a subclass

后端 未结 5 1704
情歌与酒
情歌与酒 2021-01-19 03:37

I\'m extending the functionality of a class with a subclass, and I\'m doing some dirty stuff that make superclass methods dangerous (app will hang in a loop) in the context

相关标签:
5条回答
  • 2021-01-19 03:37

    note: I'm ObjC/Cocoa newcomer:

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

    Peter

    0 讨论(0)
  • 2021-01-19 03:44

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

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

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

    To keep other code from using the superclass's version this method, you can further restrict by putting this in your .m file.

    - (int)dangerousMethod 
    {
        return nil;     
    }
    
    0 讨论(0)
  • 2021-01-19 03:46

    Just re-implement the unsafe method in your subclass and have it do nothing or throw an exception or re-implement it as safe, just as long as the new implementation doesn't call the unsafe superclass method.

    For the C++ crew in here: Objective C doesn't let you mark methods as private. You can use its category system to split up the interface into separate files (thus hiding 'private' ones), but all methods on a class are public.

    0 讨论(0)
  • 2021-01-19 03:51

    If you create the methods in your superclass as "private" then the subclass has no possible way of calling them. I'm not familiar with Objective C, but every other object oriented language I've seen has the "private" qualifier.

    0 讨论(0)
  • 2021-01-19 03:55

    This article explains how to create private variables in Objective C. They aren't truly private, but from what I read, the compiler will throw a warning if you try to call them from the subclass.

    0 讨论(0)
提交回复
热议问题