Bo A
Bo A

Reputation: 3154

Why do we normally import .h files but not .m files in Objective C?

I recently started to wonder why we usually import .h files instead of .m files in Objective C.

#import ClassName.h

Is there any benefit on importing .h files over .m files?

Upvotes: 2

Views: 1220

Answers (4)

Dustin
Dustin

Reputation: 6803

It depends what you want. The .h files have the property declarations and public methods in them. .m files have all the implementations.

Normally you're importing a .h file because you just want access to properties and methods of a class, not a recreation of its methods.

Upvotes: 1

Bradley Armstrong
Bradley Armstrong

Reputation: 67

Xcode won't allow you to import .m file it shoudl throw an error. The header file holds all of the relevant data required to import a class such as variables,delegates etc

Upvotes: -2

Kaan Dedeoglu
Kaan Dedeoglu

Reputation: 14841

You import .h files because when you import a class, your goal is to let the class know about the methods and instance variables of the imported class, and thats all you need. You don't need your class to know about the logic of the imported class. I used the word class a lot, but I hope this was clear.

Upvotes: 1

MikeS
MikeS

Reputation: 3921

The .m file is meant to be private, while the .h file is meant to be imported and used by other classes. For example, a small section of your .h file might look like this:

@property (nonatomic) NSInteger myPublicInteger;

- (void)myPublicMethod;

Your .m file on the other hand might look like this:

#import "MyClassNameHere.h"

@interface MyClassNameHere()
@property (nonatomic) NSInteger myPrivateInteger;
- (void)myPrivateMethod
@end

@implementation MyClassNameHere
@synthesize myPrivateInteger, myPublicInteger;

- (void)myPrivateMethod
{
    //some code here
}

- (void)myPublicMethod
{
    //some code here
}

Classes that import your .h file and create an instance of your class will be able to directly access myPublicInteger and send messages to myPublicMethod. However, they will not have any access or knowledge of myPrivateInteger or myPrivateMethod.

Upvotes: 2

Related Questions