Why does a simple program import <Foundation/Foundation.h> instead of individual header files?

Viewed 22949

I'm new to Objective-C. The Xcode generated template code contains:

#import <Foundation/Foundation.h>

When I check it at /System/Library/Frameworks/Foundation.framework/Headers, there are nearly 2 thousands header files!

My question is, for a really simple code that use only NSString, why not import just the NSString.h file?

Does importing the whole bunch of Foundation framework affect the performance of executables? If not, does it have some benefits?

2 Answers

As per your question as really simple code like below:

int main() {
   /* my first program in Objective-C */
  NSLog(@"Hello, World! \n");
   return 0;
}

Just trying to print "Hello World", if we don't import foundation.h framework, we will get below error:

main.m: In function ‘main’:
main.m:4:3: warning: implicit declaration of function ‘NSLog’ [-Wimplicit-function-declaration]
   NSLog(@"Hello, World! \n");
   ^~~~~
main.m:4:3: error: cannot find interface declaration for ‘NSConstantString’

Which simply means, all the basic thing which are required to execute a program are automatically included in #import . Like in this case NSLog

This just like a #include<stdio.h> in C or #inlcude<iostream.h> in c++

Related