views:

3786

answers:

2

In Objective C, if you are subclassing something, and are planning to override a method on the superclass, should you re-declare the superclass method in your subclass @interface?

For example, if you are subclassing UIViewController (e.g. MyViewController), and you are planning to override "viewDidLoad" should you include that method in your MyViewController @interface declaration, or just implement it in MyViewController.m?

In examples I've come across, I've seen it done both ways (re-declaring the method in your subclass interface, or not re-declaring the method). There may not be any functional difference, but what is the best practice?

+9  A: 

I often declare methods that I plan to override in either the public header or at least in a private category. The benefit to this is that you'll get an incomplete class definition warning if you forget to actually override the method... which comes in handy from time to time.

As for when to place it in the public header, that's pretty subjective and probably up to you/your team's coding styles. I usually only redeclare a method in the public header if I plan to radically change what the method is going to do or if I plan not to invoke the super class's version of the method.

Jason Coco
+1 That makes sense. Someone with a name like "Coco(a)" must know what he's doing.
Andy White
+2  A: 

People often use the header as documentation for the class (and tools like AutoDoc support this). Obviously, if you're following that convention, the only sensible choice is to include redefined methods so you can explain what you've done with them. Otherwise your docs for the class are either incomplete or scattered to the four corners of the earth.

But if we're just copy-pasting the declaration, I don't personally like to redeclare methods. It's not DRY and it bloats your header unnecessarily. Less code is better code.

Chuck
Also a good point
Andy White