Lets examine the standard "Hello World!" program in Objective-C. Unlike languages such as Javascript or Python, C can feel heavy on ceremony at first. But it's not really that bad. Lets go through it section by section.
//
// main.m
// HelloWorld
//
// Created by David Groulx on 4/22/14.
// Copyright (c) 2014 David Groulx. All rights reserved.
//
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
}
return 0;
}
// // main.m // HelloWorld // // Created by David Groulx on 4/22/14. // Copyright (c) 2014 David Groulx. All rights reserved. //
Any text between // and the end of a line will be ignored. Comments can also appear after
a line of code, for example:
float speed; // m/s^2
#import <Foundation/Foundation.h>;
C provides very little functionality by default. Instead we need to explicilty bring in extra libraries to do some work. Foundation is an Apple library that provides the most basic function.
int main(int argc, const char * argv[]) { ... }
Functions can be named almost anything you like, however the name main is special.
main() is always the entry point into a given
program. Unlike scripting languages which will start executing from
the top of the file, a C program always starts with a call
to main(). The arguments
to main, argc and argv, are
the number of command line arguments, and an array of strings
representing those arguments repsectively. In developing for iOS
this code will always be there, but you won't need to change or
modify it in any way. The details of function declaration will be
covered in a bit, but nfor now know there is nothing special about
the main function other than it's name.
@autoreleasepool { ... }
The '@' symbol is a feature of Objective-C. @autorelease sets up Automated Reference Counting, or ARC, Apple's solution for managing memory. Don't worry about it too much for now.
NSLog(@"Hello, World!");
This line calls the Foundation function NSLog with the argument @"Hello, World!". Again the '@' symbol means that we are using Objective-C. In this case, @"some words" creates an Objective-C string. We could use C-style strings, however string handling in C is atrocious so we'll stick with the Objective-C style when we can.
return 0;
Functions in C do not implicitly return values, instead they must
be specified by the return keyword. By convention in C,
returning a value means that the program ended without problems.