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

1

8

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.

Revest answered 29/8, 2013 at 14:14 Comment(1)
You need to remember that Objective-C is "duck typed". If a class supports a method you can (safely) invoke it, even if the method is not defined in the class's .h file. (How you sneak past the compiler checks is up to you.)Unhook
B
7

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.

Behah answered 29/8, 2013 at 14:20 Comment(1)
I suppose it just "feels" unsafe because the category method isn't as tightly coupled to the class as an instance method.Revest

© 2022 - 2024 — McMap. All rights reserved.