Here is our first Objective-C program, myFirstCode.m
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; // insert code here... NSLog(@"Hello, World!"); [pool drain]; return 0; }
The line
#import <Foundation/Foundation.h>tells the compiler to locate and process a file nemed
Foundation.h.This is a system file and
#importsays to import the information into the program as if the contents of the file were in the code at that location. The file has information about other classes and functions needed in the program.
In the line
int main(int argc, const char * argv[])The
mainis a special name that tells where the program should begin execution.
So, what the code is supposed to to?.
It's inside the main { }.
The line
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];reserves space in memory for an "autorelease pool".
The next line
NSLog(@"Hello, World!");prints out string "Hello, World!"
The @ sign with a string of characters is a constant "NSString" object. Without it it is a constant "C-style string".
The "NSLog()" function displays with the date and time it is executed, the program name etc. as in the line below.
2010-04-24 20:51:01.056 myFirstCode[322:807] Hello, World!
Before we exit your program, we should release the memory pool allocated with the line like this:
[pool drain];
<variableWithNSLog.m>
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int iPhone3GS = 250; int iPadwithWiFi = 600; int total = iPhone3GS + iPadwithWiFi; NSLog(@"Total price of iPhone and iPad = %i",total); [pool drain]; return 0; }
If you run it:
%gcc -framework Foundation variableWithNSLog.m -o myRun
%./myRunYou will get something like this:
2010-04-25 20:55:48.804 mmm[559:807] Total price of iPhone and iPad = $850