Published on 08 November 2015 Tweet
When first open an objective-C project in X-code, the .h and .m files looks 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 referencing. For example,
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 is automatically generates for you behind the scene in order to make the @property’s instance accessible:
@synthsize something = _somthing;
- (NSString *) 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…
Also, for private declarations, you can put inside the .m files like this:
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 starts to make sense :D
Originally published at victorleungtw.com on November 8, 2015.