I have a class structure of the type UIViewControllerSubclass : UIViewController
, where the only function of UIViewControllerSubclass is to #import UIViewController+Category.h
. The reason I added methods in a category is so that I can also make UITableViewControllerSubclass : UITableViewController
, which will #import UIViewController+Category.h
as well. As we all know, don't repeat yourself.
Now assume that UIViewController+Category.h has the structure:
@interface UIViewController(Category)
- (void) method1;
- (void) method2;
@end
How safe is it to create UIViewControllerSubclassSubclass : UIViewControllerSubclass
, which will override method1
? I assume this will work because of Objective-C's message passing, but for some reason my intuition is telling me that I'm doing it wrong.
You can of course overload the method multiple times (and override those), but the superclass needs to know all combinations. An alternative could be to have a single bean as the argument, and make that a generic type. Every subclass can then define the appropriate object type.
Method overloading is a programming language feature supported by Objective-C, C++, Java, and a few other languages. Using this feature, programmers can create different methods with the same name, in the same object. However, method overloading in Objective-C differs from that which can be used in C++.
An instance method that is defined in a subclass is said to override an inherited instance method that would otherwise be accessible in the subclass if the two methods have the same signature.
Extension methods cannot be overridden the way classes and instance methods are. They are overridden by a slight trick in how the compiler selects which extension method to use by using "closeness" of the method to the caller via namespaces.
Everything should work fine since the category is applied to UIViewController
, so all instances of UIViewController
, including subclasses, will have access to the methods. There's nothing unsafe about it; that's how categories are intended to be applied.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With