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

Victor Leung
2 min readNov 8, 2015

--

When first open an objective-C project in X-code, the .h and .m files look confusing. It is important to understand the simple connections and the hidden codes behind the scene.

They are used to separate between the public and private parts of the class. The .h file is a header file for public declarations of your class like an API, while the .m file is the private implementation.

When you need to call a function at the other files, just need to import the .h files for reference. For example,

#import <Foundation/Foundation.h>

In the .h file, we can declare public @property of the class, which can be called from outside:

@property (strong, nonatomic) NSString *something;

Here the @property is a pointer to an object whose class is NSString. All objects live in the heap, thus we need the *. As a side note, the strong means “keep the object points to 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 of this property are automatically generated for you behind the scene in order to make the @property’s instance accessible:

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

Notice that by default the backing variable’s name is the same as the property’s name 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 .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 put inside the .m files like this:

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

Finally, when you are reading other codes for the first time, just need to look at the .h files to give you an overview of the projects, unless you need to deep dive in the details, then look at the .m files.

Understanding the above fundamental concept and the rest of the code would start to make sense :D

Originally published at victorleungtw.com on November 8, 2015.

--

--

Victor Leung
Victor Leung

Written by Victor Leung

I write about business, technology and personal development

No responses yet