Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to override a Category-defined method in Objective-C? [duplicate]

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.

like image 542
paulrehkugler Avatar asked Aug 29 '13 14:08

paulrehkugler


People also ask

Can you override a method more than once?

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.

Does Objective-C support method overriding?

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++.

Can you override an instance method?

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.

Can we override method in extension?

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.


1 Answers

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.

like image 173
Bryan Chacosky Avatar answered Oct 16 '22 09:10

Bryan Chacosky