Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.h and .m files in Objective-c [closed]

Tags:

objective-c

I'm on a quest for knowledge today.

I'm working on some code for work, and after review I had a complete Brain Fart and can't remember why we do something with the .h and .m files in objective-c

  1. I was wondering why do we import files and declare method names in the .h files? (I know it has to do with processing, but can't remember the details)
  2. Why do we sometimes import files directly into the .m file and not in the .h files in some cases.
  3. When you declared a method in the .h file are you doing this because the class and/or libraries you are using don't perform a function you need them too?
  4. Is there ever a case where you declared a method that doesn't exist in any of your libraries or your .h file in your .m file?

Thanks everyone I hope that all made sense.

like image 297
Jadex1 Avatar asked Jul 09 '13 21:07

Jadex1


2 Answers

  1. It's used to separate between the public and private parts of a class. The .m file is the implementation. It is where all the logic goes, all the data is processed and stored, etc... The .h file is the interface of that class. It's literally like an API for your own class. It tells other classes how to use it and how to interface with it.

  2. You import a class when you reference it in a file. If you reference something (i.e. a property) in the interface then you import it in the .h. If you only reference it in the implementation then you import it in the .m.

  3. Any methods declared in the .h are there so that other classes know that they can run it. i.e. they are public methods. Try and remove a declaration and then call that method. You'll get a warning.

  4. No, this wouldn't make sense. Unless you were part way through writing your program and declared it for testing purposes.

like image 188
Fogmeister Avatar answered Sep 20 '22 18:09

Fogmeister


  1. Because the .h file is the class's public interface
  2. Because putting the imports into the .m file makes them private and keeps the dependencies out of the .h file (prevents excessive dependency importing and potential circularities)
  3. You're doing it to publicly state that you provide that service
  4. You shouldn't, if it doesn't exist you can't use it (though you may declare things that you hope will exist and check before you actually try to use them)

Bonus extra for 2. In your .h file you should endeavour to have the minimum number of imports possible (just the superclass and any protocols you publicly implement) and use @class for everything else. This minimises the dependency implications.

like image 43
Wain Avatar answered Sep 19 '22 18:09

Wain