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
note: I'm ObjC/Cocoa newcomer:
@implementation MyClass
-(void)myMethod:(NSString *)txt{
if([self class] != [MyClass class]) return;
NSLog(@"Hello");
}
@end
Peter
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;
}
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.
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.
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.