iOS Objective-C Hello World Example

Objective-C is the primary coding language in iOS development. For every iOS coding beginner, it is important to learn the hello world example first. This article will introduce Objective-C’s basic programming grammar,  code structure and commonly used classes with examples.

1. Objective-C Hello World.

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]){
    /* When the @autoreleasepool decorated code block complete, 
       all the temporary variables (in the code block) used memory 
       will be recycled automatically.*/
        // @ means the String is a NSString type string. 
        NSLog(@"Hello World Objective-C");
    return 0;

Above method is equivalent to java’s main method. Found.h is the header file in the Foundation framework, it is a basic class library for Objective-C.

There are two directive to include header files, #include and #import. If use # include directive alone will result in importing duplicate library files, causing error reporting.

So we can use #import directive, it is #include directive’s enhancements that effectively handle repeated imports without error reporting.

Import the system class library with <>, import the custom class library with””.

2. Classes Declaration.

2.1 Objective-C Class Declaration.

Employee.h is the header file, you should put below code in it.

@interface Employee : NSObject{
    //property declaration
    //method declaration
    -(void) helloWorld;

@interface is equivalent of java’s class, the colon(:) after Employee is equivalent of java’s extends.

2.2 Objective-C Class Implementation.

Employee.m is the implementation file, put below code in it.

@implementation Employee
    //method implementation

       NSLog(@"Hello World");


3. Methods.

3.1 Object Instance Method Declaration.

The minus sign begin method is an object method. The method’s return and argument parameter type must be enclosed in parentheses. The formal parameters of the function are denoted by a colon.

Syntax: – (return value type) method name: (parameter type) parameter name.

@interface Employee : NSObject
     // Below is a instance method declaration, it has three argument, userName, password and email.
     -(Void) regist:(NSString * )userName setPassword:(NSString * ) password setEmail:(NSString *) email;

3.2 Class Method Declaration.

The plus sign represents the static method (class method).

Syntax: + (return value type) method name: (parameter type) parameter name.

@interface Employee : NSObject
      +(Void) login:(NSString * )userName setPassword:(NSString * ) password;

3.3 Different Between Object Method And Class Method.

Object methods can access properties directly, while class methods can not. Class methods can be invoked directly with class name, but object methods can not.

4. Class Constructor.

4.1 The Default Constructor.

instancetype means this method return a Objective-C object.

- (instancetype)init{
    if(slef = [super init]){
         // Initializztion code.
    // Return newly constructed object.
    return self;

4.2 Custom Constructor.

Most custom constructors start with init, this do not override the system default constructor, this is to add a new constructor.

- (instancetype)initWithUserName:(NSString *) userName{ 
     if(slef = [super init]){ 
          //Init object name property. 
 = userName; 
      return self; 

5. Create A New Instance.

There are two methods for you to create an Objective-C object, new and alloc, init. The difference between them are:

  1. The new method can only use default init method to initialize the object.
  2. But the alloc method can use a custom initialize method.

5.1 Use new Method.

Inside the new method, alloc and init are called separately in order. alloc method is used to allocate storage space and returns the assigned object. init method is used to initialize the returned object.

Employee *employee=[Employee new];

5.3 Use alloc and init Method Manually.

alloc is a class method and init is a object method. alloc method just return an object of the class, init method will initialize all the object properties value to 0 by default.

Employee *employee=[[Employee alloc] init];

Please Note : After the default initialization is complete, all member variables value will be initialized to 0. When you do not want to use an object you should release it’s related memory with below code.

[employee release];

6. Access Object Property.

syntax: object -> property name


7. Call Object Methods.

7.1 Call No Argument Method.

Syntax :[object name method name]

[employee work]

7.2 Call Method With Arguments.

Syntax :[object name method name: parameter]

[employee register:@"Tom" password:@"888888" email:@"[email protected]"]

8. @property And @synthesize.

8.1 @property.

@property is used to declare properties in the header file. With this declaration, the compiler will makes up its set and get methods automatically.

@property int age;

8.2 @synthesize.

@synthesize is used to implement property in a m file. The compiler generates implementations of set and get methods automatically.

@synthesize age;

9. Get & Set Methods.

9.1 Declare Object Property Set & Get Method.

#import <Foundation/Foundation.h>
@interface Employee : NSObject{
        // Declare property.
        NSString * _userName;

      // Declare property set method.
      - (void)setUserName:(NSString *) userName;
      // Declare property get method.
      - (NSString *)userName;


9.2 Implement Property Set & Get Method.

#import "Employee.h"
@implementation Employee

      // Implement set method.
      - (void)setUserName:(NSString *) userName{
         _userName = userName;

      // Implement get method.
      - (NSString *)userName{
        // Return _userName property.
        return _userName;


9.3 Property Get & Set Method Usage Example.

#import <Foundation/Foundation.h>
#import "Employee.h"

int main(int argc, const char * argv[]){
    @autoreleasepool {
        Employee *employee = [[Employee alloc] init];

        // Dot syntax,equivalent [employee setUserName:@"Tom"];
        employee.userName = @"Tom";

        // equivalent to [employee userName];
        NSString *userName = employee.userName;

        NSLog(@"UserName is %s", userName);
        [employee release];
     return 0;

10. Static Property.

The static properties in objective-c are private global variables. It can not be accessed directly by the class name. It only works in the .m file where it is declared.

Although the static property is private, but they can be accessed externally by static methods.

10.1 Define private static variables and public static methods in h files.

#import <UIKit/UIKit.h>
// Declare static property, this property is private,
static int index;

@interface Custom_TabBar : UITabBarController
    // Declare public static method with plus prefix.

10.2 Override the static method in the class .m file.

   // Return the static variable index.
   return index;

10.3 Use above static variable in other class.

  1. First import the header file in the h file.
    #import "Custom_TabBar.h"
  2. Obtained Custom_TabBar’s private static variable’s value directly in .m file use the public static method getIndex.
    if([Custom_TabBar getIndex] < 0){

11. NSString.

NSString is an Objective-C defined string class, it provide a lot of method for string manipulation.

// Create NSString with default value.
NSString * str = @"Hello Objective-C";

// Get string length
[str length]

// Create an empty new NSString.
NSString * str1 = [NSString new]

// Create a new NSString str2 and copy str1's value to it.
NSString * str2 = [[NSString malloc]initWithString:str];

// Create a new NSString str3 with formated string value.
NSString * str3 = [NSString  stringWithFormat:@"Hello %@ - %@",@"Objective",@"C"];

// Concat two string value to a new string.
NSString *newString = [NSString stringWithFormat:@"%@%@",str1,str2];

11.1 String Numeric Type Conversion.

// string to int.
int int1 = [str1 intValue];

// int to string.
NSString *str1 = [NSString stringWithFormat:@"%d",int1];

// string to float.
float float1 = [str1 floatValue];

// float to string.
NSString *str1 = [NSString stringWithFormat:@"%f",float1];

12. NSLog.

A util class to print string data in stdout such as terminal console.

// Create a NSString address pointer. 
NSString *str = "Good Morning";
NSLog(@"str's pointer address = %p, str's value = %@ ",str,str);

// Print NSString, need to add @ before string text.
NSLog(@"Hello Objective-C");

// Print string text in C program language.
printf("Good Morning");

13. NSMutableArray VS NSArray.

NSMutableArray is a length changeable array. That is when the element in front of the array is deleted, the next element will move forward. NSArray is a length unchangeable array.

// Create an empty NSMutableArray
NSMutableArray *array = [NSMutableArray array];
// Add element
[array addObject:@"hello"];
// Remove element
[array removeObject:@"hello"];
// Remove all element.
[array removeAllObjects];
// Get element at specified index

14. NSBundle.

An NSBundle is a directory that contains the resources that the program will use, it equivalent to the home directory folder in the project.

NSBundle is most frequently used to get the Plist file and it’s content. The Plist file can be simply understood as a small database type file. By default, an info.plist file is created when the project is initialized to store the default configuration information for the system.

// Print sandbox path.
NSString *homeDir = NSHomeDirectory();

// Create NSBundle
NSBundle *bundle = [NSBundle mainBundle];

// Two ways to get the path of logo.jpg files in an NSBundle
NSString *path = [mainBundle pathForResource:@"logo" ofType:@".jpg"];
NSString *path = [mainBundle pathForResource:@"logo.jpg" ofType:nil];

// Get Plist file in NSBundle.
NSString *plistPath = [mainBundle pathForResource:@"info.plist" ofType:nil];

// Get dictonary by Plist path.
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:plistPath];

// Get NSArray by Plist path
NSArray *array = [NSArray arrayWithContentsOfFile:plistPath];

15. NSDate.

// Get current date.
NSDate *currentDate = [NSDate date];

// Get NSDateFormatter object.
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];

// Set new date format.
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";

// Format current date to a string use above formatter.
NSString *date = [formatter stringFromDate:currentDate]

16. KeyValue Coding (KVC).

KVC is a mechanism by which class attributes can be accessed directly by the name (key) of the string, instead of calling setters and getters method.

16.1 Set the properties in KVC mode.

Employee *employee = [[Employee alloc] init];
[employee setValue:@"Tom" forKey:@"userName"];
[employee setValue:@"[email protected]" forKey:@"email"];

16.2 Get the properties in KVC mode.

NSString *userName = [employee valueForKey:@"userName"];