13
votes

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

2 Answers

21
votes

It doesnt affect the performance as the inbuilt frameworks are all there installed on your device already ready to be linked to by your executable.

What you are saying when you #import <Foundation/Foundation.h> is "I would like access to the functionality of the Foundation framework even if I don't use it all". Its a semantic division.

The compiler will do all the optimisation that needs doing with respect to discarding unused symbols.

The problem with just doing an import on NSString.h is do you know what dependencies there are for NSString. I don't know, and dont need to either.

0
votes

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++