user1452574
user1452574

Reputation: 485

Guidelines for declaring methods in @interface, in an extension, or not declaring at all

I've been learning Object Oriented Programming in Objective-C and I'm a little confused about method declaration and implementation.

In some lectures I've been studying, the professor declares public methods in the .h file and then implements them in the .m file; or he may declare them private in the .m file and them implement them in the @implementation ClassViewController section.

Sometimes, however, he doesn't declare methods at all and just skips to method implementation in the @implementation ClassViewController section.

How do I make this distinction where to declare something either public or private, or not having to declare anything at all?

Upvotes: 2

Views: 142

Answers (2)

CrimsonDiego
CrimsonDiego

Reputation: 3616

Methods should be declared publicly when you want that method to be accessible to outside classes, and privately otherwise. A method that was declared in a superclass does not need to be declared again in it's subclasses if you override it. As far as methods that are implemented without any previous declaration, that method can still be called, but it is only 'visible' to methods below it in the file, and will throw a warning otherwise. As such, this is rarely done (it is declared privately instead), with the exception of if that method is intended to be the target of an @selector.

Upvotes: 2

Firoze Lafeer
Firoze Lafeer

Reputation: 17143

The short answer is that all methods should be declared (either publicly or privately).

But I suspect what you actually saw your professor do was override a method that was already declared in a superclass.

So for example, if you wanted to override viewDidLoad in your CustomViewController, you would not declare viewDidLoad again, because that method was already declared in the header for UIViewController (the superclass).

You would simply go to the implementation of your subclass and write your implementation of viewDidLoad which would override the one you inherited. If you go watch the lecture again, I'm guessing that is what you saw.

Upvotes: 1

Related Questions