skip to Main Content

Recently i switched to a project which was mainly written in objective-c which i am pretty new to, but in one file i was surprised to see only a .m file and as usual .h file was missing. But still the code works properly. My question is .h file not mandatory? Can they be merged into a single .m file. There is a sample code snippet of .m file which i found.

The code snippet is:

#import "CusView.h"
@interface MyFile: ViewController {
}
@property (nonatomic, retain) NSString *someProp;
-(void) fillTheText : (NSString*)text;
@end
@implementation MyFile
-(void) fillTheText : (NSString*)text {
NSLog(@"Print here")
}
@end

2

Answers


  1. Technically, it’s possible to include everything to your m-file. See also here and the item 3 below.

    Regarding your specific example:

    1. Did you search the project for the h-file? It might be put into some other folder.

    2. Did you check if MyFile is used anywhere in code? It could be just unused and not imported anywhere.

    3. Did you check how MyFile imported where it’s used? It’s probably just imported with the m-file.

    Login or Signup to reply.
  2. Fundamentally, there is nothing magic about the location of the code in C or Objective-C. You can put the @interface in the .m or the @implementation in the .h. You could have multiple @implementations for the same class spread out across multiple files and either compile them separately (class extensions) or, even, #import them.

    Of course, just because you can doesn’t mean you should. This is more just to point out that the compiler really doesn’t care where the code comes from, it just cares about the actual contents of whatever is being compiled.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search