Connection between .h and .m files in Objective-C

November 08, 2015

When you first open an Objective-C project in Xcode, the .h and .m files may look confusing. It's important to understand the simple connections and the hidden code behind the scenes.

2015 11 08

These files are used to separate the public and private parts of the class. The .h file serves as a header file for public declarations of your class, functioning like an API, while the .m file contains the private implementation.

When you need to call a function from other files, you just need to import the .h file for referencing. For example,

    #import <Foundation/Foundation.h>

In the .h file, you can declare public @property attributes of the class, which can be accessed from outside:

    @property (strong, nonatomic) NSString *something;

Here, @property is a pointer to an object whose class is NSString. All objects live in the heap, so we need the asterisk (*). As a side note, "strong" means "keep the object in memory until I set this property to nil." "Nonatomic" means "access to this property is not thread-safe;" otherwise, the compiler will generate locking code.

In the .m file, the "getter" and "setter" methods for this property are automatically generated for you behind the scenes to make the @property instance accessible:

    @synthesize something = _something;
    - (NSString *) something
    {
      return _something;
    }
    - (void)setSomething:(NSString *)something
    {
      _something = something;
    }

Note that by default, the backing variable's name is the same as the property's name but with an underscore in front. You don't need to write the above code unless you want to override the method and do something differently.

When you create a new method, you need to put the declaration in the .h file:

    - (int)newMethod:(ArgType *)arg;

And then write the actual details in your .m file.

    - (int)newMethod:(ArgType *)arg
    {
      int num = 0;
      // something in the method...
      return num;
    }

Also, for private declarations, you can include them in the .m file like this:

    @interface Something()
    // private declarations...
    @end

Finally, when you are reading other people's code for the first time, you just need to look at the .h files to get an overview of the projects. If you need to delve into the details, then look at the .m files.

Understanding the fundamental concepts outlined above will make the rest of the code start to make sense. :D


Profile picture

Victor Leung, who blog about business, technology and personal development. Happy to connect on LinkedIn