iOS: Hello World using Objective-C Class and IBAction

iOS applications use Cocoa classes, and these classes use the Objective-C programming language so one must know Objective-C if he/she does wish to develop iOS apps. We all know shifting from a loss, non-strict programming language might find iOS’s syntax seem strange and difficult. Don’t worry, this strangeness and difficulties will give way to an elegant experience programming in iOS and I am sure that everyone will appreciate the meticulous language to become an MVC methodologist.

Class @interface and @implementation

iOS separates a class into an @interface and @implementation. An interface declares instance variables, properties and methods. It is a standard C header file and doesn’t provide any method definitions. The implementation, however, contains the method definitions for the class and this is the place where you synthesize the properties. It is the file in a .m extension.

Creating a project with Objective-C Class file

We will create an example project using an Objective-C class and IBAction. First, create a View-Based Application project and name it ClassAndIBAction. After creating the project, single-click the ClassAndIBAction folder and create a new Objective-C Class file. Go to File > New > New File or create the file by pressing Command + N (⌘ + N) buttons and pick Objective-C Class file.

iOS: Hello World using Objective-C Class and IBAction - Create New File

Pick NSObject as subclass press next and name the file HelloWorld. Once the file gets created single-click HelloWorld.h and it should contain codes similar to this:

#import <Foundation/Foundation.h>

@interface HelloWorld : NSObject {
    
}

@end

We will start coding here. First, we will create instance variables:

NSString *name;

then, we will create a class method and an instance method:

- (void)sayHelloTo: (NSString *)name withAge: (NSInteger)age;
+ (NSString *)getName;

An Instance method, in a typical implementation, is passed a hidden reference (e.g. this, self or Me) to the object (whether a class or class instance) it belongs to, so that it can access the data associated with it.

For Class methods; a typical example of a class method would be one that keeps count of the number of created objects within a given class.

Simply, instance methods use an instance of a class, whereas a class method can be used with just the class name.

Now, how to determine which is which between an instance and a class method? Easy, by determining the very first character of the line. Yes, the + and the - sign. Instance method should start with a minus (-) sign and the class method should start with a plus (+) sign.

The whole HelloWorld.h file should look like this:

#import <Foundation/Foundation.h>

@interface HelloWorld : NSObject {
    NSString *name;
}

- (void)sayHelloTo: (NSString *)name withAge: (NSInteger)age;
+ (NSString *)helloWorld;

@end

Many languages implement a variable the same way Objective-C does. The type first, then, the name comes second.

iOS: Hello World using Objective-C Class and IBAction - Variable Type and Variable Name

Note: The four basic types of C are char, int, float, double. Of course, this expanded in Objective-C.

Next, we declared a method. 2 methods, an instance method and the other a class method. The declaration in Objective-C is unique since this is the only language (correct me if I’m wrong) that declares methods such as this.

iOS: Hello World using Objective-C Class and IBAction - Method Structure

Note: You can add as many method arguments as you like and you can also create a method without an argument at all.

For the instance method, it’s expecting to return nothing (void) and takes an NSString and an NSInteger for the first and second argument. For the class method, it’s expecting an NSString and takes no argument.

iOS: Hello World using Objective-C Class and IBAction - Interface Structure

Note: I am using a different Xcode theme (Dusk) so the color scheme may be different with the one you’re using.

@interface anatomy

An interface consists of import statements, class declaration, instance variables, property declarations, method declarations just like the image above.

First we imported the Foundation framework header. The Foundation framework defines a base layer of Objective-C classes. In addition to providing a set of useful primitive object classes, it introduces several paradigms that define functionality not covered by the Objective-C language. The Foundation framework is designed with these goals in mind:

  • Provide a small set of basic utility classes.
  • Make software development easier by introducing consistent conventions for things such as deallocation.
  • Support Unicode strings, object persistence, and object distribution.
  • Provide a level of OS independence, to enhance portability.

The Foundation framework includes the root object class, classes representing basic data types such as strings and byte arrays, collection classes for storing other objects, classes representing system information such as dates, and classes representing communication ports. Go here: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/
ObjC_classic/Intro/IntroFoundation.html
to learn more about the Foundation framework.

After importing the Foundation framework, we declared the @interface directive with HelloWorld as the class name and NSObject. NSObject is the root class of most Objective-C class hierarchies. Through NSObject, objects inherit a basic interface to the runtime system and the ability to behave as Objective-C objects. To know more about NSObject, you can go here: http://developer.apple.com/library/mac/
#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html

We declared the instance variable NSString *name inside the @interface directive, then, we declared the property and the methods at the end outside of the @interface directive.

@implementation anatomy

There, our class interface is finished. Next will be implementing our class @implementation file. The implementation file should look like this:

#import "HelloWorld.h"

@implementation HelloWorld

@synthesize name;

- (void)sayHelloTo: (NSString *)username withAge: (NSInteger)age
{
	[self setName: username];
	NSLog(@"Hi I'm %@ and I'm %i years old", username, age);
}

+ (NSString *)helloWorld
{
	return @"Hello World";
}

@end

For the implementation file, we imported the HelloWorld.h file, yes, the header file of our HelloWorld class. Then, we declared the @implementation directive. After that, we @synthesized our instance variable name.

@synthesize name;

Then we implement our methods:

- (void)sayHelloTo: (NSString *)username withAge: (NSInteger)age
{
	[self setName: username];
	NSLog(@"Hi I'm %@ and I'm %i years old", username, age);
}

+ (NSString *)helloWorld
{
	return @"Hello World";
}

For the instance method, we have an NSString argument name and an NSInteger argument called age. Inside the method, we set the name from the first argument username, then we displayed a message using NSLog.

For the class method, we have a method without an argument that should return an NSString. In this case, we will return a static string Hello World.

ClassAndIBActionViewController.h

We’re almost finish. We just need to implement our class. Single-click (or double-click if you want a separate editor) ClassAndIBActionViewController.h and add an #import directive and an instance variable.

#import "HelloWorld.h"
// Don't forget to create a @property
HelloWorld *helloWorld;

The whole code should look like this:

#import <UIKit/UIKit.h>
#import "HelloWorld.h"

@interface ClassAndIBActionViewController : UIViewController {
    HelloWorld *helloWorld;
}

@property (nonatomic, retain) HelloWorld *helloWorld;

@end
ClassAndIBActionViewController.m

After creating the @interface we will implement it. Single-click ClassAndIBActionViewController.m and update the code. First, we synthesize the variable helloWorld:

@synthesize helloWorld;

Of course, don’t forget to release the instance variable we created. Add this inside the dealloc method and nil out variables that can easily be reproduced in the viewDidUnload method:

// dealloc
[helloWorld release];
// viewDidUnload
[self setHelloWorld: nil];

After that, we will now need the viewDidLoad method (uncomment the method if it is commented out). We will now initialize the helloWorld variable using the alloc and init methods.

// viewDidLoad
helloWorld  = [[HelloWorld alloc] init];

After the initialization, we will now implement the method we created:

- (IBAction)buttonTapped:(id)sender
{
	helloWorld  = [[HelloWorld alloc] init];
	[helloWorld sayHelloTo: @"Angelo" withAge: 23];
	NSLog(@"%@", [HelloWorld helloWorld]);
}

Note: IBAction let’s Interface Builder know that the method can be connected to a button.

Almost there, we just need to create a button and connect it to the method. Single-click (double-click if you want a separate editor) ClassAndIBActionViewController.xib and create a button. Then connect the button to the IBAction method.

iOS: Hello World using Objective-C Class and IBAction - Interface Builder

Note: If you don’t know how to connect a button to a method then navigate to my previous post: iOS: Hello World. There’s a section there explaining in detail how to connect the two.

First, we called the instance method using the helloWorld instance, then, our class method. You should have a similar implementation file as this:

#import "ClassAndIBActionViewController.h"

@implementation ClassAndIBActionViewController

@synthesize helloWorld;

- (IBAction)buttonTapped:(id)sender
{
	[helloWorld sayHelloTo: @"Angelo" withAge: 23];
	NSLog(@"%@", [HelloWorld helloWorld]);
}

- (void)dealloc
{
	[helloWorld release];
	[super dealloc];
}

#pragma mark - View lifecycle
- (void)viewDidLoad
{
	[super viewDidLoad];
	helloWorld  = [[HelloWorld alloc] init];
}

- (void)viewDidUnload
{
	[self setHelloWorld: nil];
	[super viewDidUnload];
}

@end

Let’s try our App

Click the Run button on the top left corner of Xcode, after tapping, iOS Simulator will open. Once the app is running in the iOS Simulator, click the button and it will display a message in the console similar to this:


2011-04-21 22:52:35.844 ClassAndIBAction[5494:207] Hi I’m Steve and I’m 56 years old
2011-04-21 22:52:35.846 ClassAndIBAction[5494:207] Hello World

Wrapping things up

You now have the knowledge how to create an Objective-C class and an IBAction for your upcoming projects. What we did here was to create an instance method and a class method, a method with an IBAction, and created a new Objective-C class file.

Of course, we also learned the anatomy and structure of the @interface and @implementation file.

Angelo Villegas is an iOS Software Engineer from Manila. Building native iOS apps using Xcode, Objective-C and Swift, contribution to the open-source community and writing articles on AngeloVillegas.com

2 thoughts on “iOS: Hello World using Objective-C Class and IBAction”

  1. Hello

    You explain some of the basic stuff – which is always the hardest part!- really well.

    I’ve been working on really getting a handle on objective-c, trying to do lots of examples/tutorials outside of Interface Builder. Every once in a while, I slip back into a GUI environment and work to make simple alterations to sample code.

    I am working with a tutorial that defines a method called ‘process’ which is similar to your ‘buttonTapped’, in that the method does not return any value directly, yet the format of the – uh oh I forget what it’s called – (the prototype maybe?) the first line before the { that gives the method name and any return type.

    So both your buttonTapped method and my process method, don’t show any values being returned. Yet I know my code works, and I bet yours does too.

    Is it some mysterious thing about using protocols? Or something else I don’t get?

    I’m trying really to move beyond just editing a few lines and really try to understand what the code is doing.

    (here’s your code sample)
    – (IBAction)buttonTapped:(id)sender
    {
    helloWorld = [[HelloWorld alloc] init];
    [helloWorld sayHelloTo: @"Angelo" withAge: 23];
    NSLog(@”%@”, [HelloWorld helloWorld]);
    }

    1. Hi,

      The sample code consist of the HelloWorld class with a instance method that has a string and integer for the first and second argument respectively. The third link inside the curly brace is a NSLog function. The helloWorld as a class method that will return the string “Hello World”. The IBAction inside the open and close parentheses tells Xcode that it is action that can be connected to an existing button in Interface Builder. The “(id)sender” after the colon is the object (button) who triggered the event “button tapped”.

      I hope this clear things up.
      Angelo

Do you like the post, have a question or want to clear something out? Leave a comment...