2

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Recent versions of Clang actually no longer complain about undeclared methods defined out-of-order.
Oh really? Well that's useful to know.
1

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.

1 Comment

That second sentence is very insightful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.