Alex Rivera | Logout

When do I define objective-c methods?

Asked 2009-06-19T21:21:24.577
34

I'm learning Objective-C, and have a C/C++ background.

  • In object-oriented C++, you always need to declare your method before you define (implement) it, even if it is declared in the parent class.

  • In procedural-style C, IIRC, you can get away with just defining a function so long as it is only called from something else in the same compilational unit (ie. the same file) that came later on in the file (well, provided you don't declare it elsewhere with "extern").

  • Now, in Objective-C, it appears that you only need to declare selectors in the header file if they are going to be used by something external, and that you can make up selectors in your .m file just fine, and call them within the .m file. Also, it appears that delegate methods or inherited methods are never (re)defined.

Am I on the right track? When do you need to define a selector in Objective-C?

Edit
Report

1 Answer

6

Declaring the methods in the header file will only stop compiler warnings. Objective-C is a dynamic language, so you can call a method (send a message) to an object whether or not that method is declared externally.

Also, if you define a method in the .m file above any code that calls it (lazy declaration) then that won't generate any warnings. However the same thing applies, you can send a message to an object without it being declared.

Of course - this means that there are no private methods in Objective-C. Any method that a class implements can be called.

Personal preference. If it's a public method (i.e one used externally). declare it in the .h and define in the .m. If you want to limit it's visibility, or at least indicate that it is a private method, use categories/class extensions in the .m file. Although lots of example code uses the lazy declaration method.

answered 2009-06-19T21:31:36.723

Your Answer