Skip to content

July 15, 2012

Quick Guide to Objective C – Introduction (Part 1)

by noise

This is first tutorial from a series of tutorials about programming in Objective C language. We want this guide to be a very practical intro to Objective C.

Objective C is mainly used to write applications for OSX (Apple’s Operating System) and for iOS (mobile Apple Operating System). But you can also write programs in Objective C compile and run them on Linux, BSD (and other UNICES) and even on Windows using Objective C support from gcc or clang compiler and GNUStep opensource libraries.

If you want to learn Objective C on Windows, here is a quick tutorial to configure and compile Objective C programs under Windows: Quick Guide Objective C and GNUStep on Windows.

If you want to learn Objective C using an open source platform here is a tutorial to configure and compile programs in Objective C under FreeBSD: Quick Guide on Objective C and GNUStep for FreeBSD.

Similar approach could be done to compile Objective C programs in Linux. Later we will write a tutorial that describe Objective C development under Linux.

Still in this tutorial for our purpose we will use OSX Operating System and XCode Integrated Development Environment (IDE).

1. First App

We’ll run XCode and we’ll write a first app in OSX. Please make the difference between OSX which is the OS for desktop/laptop machines and iOS which is the OS for mobile devices (iPhone, iPod and iPad).

So start XCode and create a new project by clicking on: File -> New -> Project.

From there we will choose from section Mac OSX: Application -> Command Line Tool like in the following picture.

Then we press Next button, we fill in a name for our project (for example you could name the app: first_app) and we choose Foundation. If you want you can write apps in C or C++, in that case you will choose C or C++, but for our tutorial we will need Foundation (see next picture).

By clicking to first button: Show the project navigator from left of XCode project window we will see our project file (see next picture).

We will click on main.m which contains our main() function. We will modify the string from NSLog function and we will compile and run the app by clicking Run button or by hitting Command + R on our keyboard.

That is our first app. To see the output we will look on console window from the bottom of our XCode project window. If we do not see the console we can activate it by clicking on XCode: View -> Debug Area ->Activate Console.

2. Working With Numbers

When programming in Objective C we can also use C or C++ code, so we have for example intergers that are defined in C using int. So the following program will compile and run:

#import <Foundation/Foundation.h>
 
int main(int argc, const char * argv[])
{
 
    int a = 10, b = 15, sum;
 
    sum = a + b;
 
    printf("Sum = %d", sum);
 
    return 0;
}

But Objective C has a new type called NSInteger which has the advantage of having bigger size on 64 bit architectures. So if you do not want to worry when to use long instead of int on some architectures you will use NSInteger. Probably this is the best approach for any Objective C app.

So our example would be:

#import <Foundation/Foundation.h>
 
int main(int argc, const char * argv[])
{
 
    NSInteger a = 10, b = 15, sum;
 
    sum = a + b;
 
    printf("Sum = %ld", sum);
 
    return 0;
}

Note: When you create an OSX Project in XCode you will see that the main block is enclosed between @autorelease { } section. In our example we did not use that because if you are using GNUStep instead of XCode (native libraries from OSX) @autorelease might not be recognized.

3. Working With Strings

3.1 Defining a String

To define a string we will use NSString type:

#import <Foundation/Foundation.h>
 
int main(int argc, const char * argv[])
{
    NSString *str1 = @"This is a string";
 
    NSLog(@"String str1 = %@", str1);
 
    return 0;
}

3.2 Concatenate Strings

In next example we will concatenate str1 and str2 and the result will be copied into str3:

#import <Foundation/Foundation.h>
 
int main(int argc, const char * argv[])
{
 
    NSString *str1 = @"This is a string";
    NSString *str2 = @"This is another string";
    NSString *str3;
 
    NSLog(@"String str1 = %@", str1);
    NSLog(@"String str2 = %@", str2);
 
    str3 = [str1 stringByAppendingFormat:str2];
 
    NSLog(@"String str3 = %@", str3);
 
    return 0;
}

It is also possible to concatenate two strings (str1 and str2) and place the result in one of those two string, for example in str1:

#import <Foundation/Foundation.h>
 
int main(int argc, const char * argv[])
{
 
    NSString *str1 = @"This is a string";
    NSString *str2 = @"This is another string";
 
    NSLog(@"String str1 = %@", str1);
    NSLog(@"String str2 = %@", str2);
 
    str1 = [str1 stringByAppendingFormat:str2];
 
    NSLog(@"String str2 = %@", str1);
 
    return 0;
}

3.4 Copy Strings

We can also copy a string to a new string (which could be also done with stringByAppendingFormat method) using stringWithFormat method:

int main(int argc, const char * argv[])
{
    NSString *str1 = @"This is a string";
    NSString *str2;
 
    str2 = [NSString stringWithFormat:@"%@", str1];
 
    return 0;
}

4. Working With Arrays

4.1 Defining an array

To define an array we will use NSArray type:

NSArray *array1 = [NSArray arrayWithObjects:@"green",\
     @"red", @"blue", nil];

We can also define an array with just one element:

NSArray *array2 = [NSArray arrayWithObject:@"green"];

4.2 Iterating through an array

See the next code:

#import <Foundation/Foundation.h>
 
int main(int argc, const char * argv[])
{
    NSInteger i;
    NSArray *array1 = [NSArray arrayWithObjects:@"green",\
                       @"red", @"blue", @"yellow", nil];
 
    for (i = 0; i < [array1 count]; i++) {
        NSLog(@"%@", [array1 objectAtIndex:i]);
    }
 
    return 0;
}

As you’ve noticed we used [array1 count] to find out the number of elements within our array and then we printed using NSLog every value from index 0 to number of elements – 1 (-1 is neccessary since we start from 0). To find every element in array we’ve used [array1 objectAtIndex:i] where i is the position in our array.

4.3 Iterating through an array using fast enumeration

We can also use Objective C’s fast enumeration to loop through elements on an array, in that case there’s no need for an index, the for loop will know to iterate through the array (this example might not work with GNUStep):

#import <Foundation/Foundation.h>
 
int main(int argc, const char * argv[])
{
 
    NSArray *array1 = [NSArray arrayWithObjects:@"green",\
                       @"red", @"blue", @"yellow", nil];
 
    for (NSString *element in array1) {
        NSLog(@"%@", element);
    }
 
    return 0;
}

4.3 Inserting an element in an array

To insert an element in our array we will use addObject method. See next example where we’ve inserted an object which value is blue and then we’ve iterated through the array to display every object:

#import <Foundation/Foundation.h>
 
int main(int argc, const char * argv[])
{
 
  @autoreleasepool {
 
    NSMutableArray *array1 = [NSMutableArray arrayWithObjects:@"green",\
                       @"red", nil];
 
    [array1 addObject:@"blue"];
 
    for (NSString *element in array1) {
        NSLog(@"%@", element);
    }
 
   } 
    return 0;
 
}

Note that we were able to modify our array because we’ve used NSMutableArray type which can be modified, and not just NSArray. The object was added to at the end of the array.

4.4 Deleting an element from an array

In the next example we delete an element from index 2 which is the third element from our array since counting starts from 0 (zero). For our purpose we’ve used removeObjectAtIndex function:

#import <Foundation/Foundation.h>
 
int main(int argc, const char * argv[])
{
 
  @autoreleasepool {
 
    NSMutableArray *array1 = [NSMutableArray arrayWithObjects:@"green",\
                       @"red", @"blue", @"magenta", nil];
 
    [array1 removeObjectAtIndex:2];
 
    for (NSString *element in array1) {
        NSLog(@"%@", element);
    }
 
   } 
    return 0;
 
}

After removing the object our array will contain: green, red and magenta.

If we want to remove last object from the array we will use:

  [array1 removeLastObject];

4.5 Copy an array to a another array

To copy an array to a new array we will use arrayWithArray method. Then we will iterate through array2 to display its values:

#import <Foundation/Foundation.h>
 
int main(int argc, const char * argv[])
{
 
  @autoreleasepool {
 
    NSArray *array1 = [NSMutableArray arrayWithObjects:@"green",\
                       @"red", @"blue", @"magenta", nil];
    NSMutableArray *array2;
 
    array2 = [NSArray arrayWithArray:array1];
 
    for (NSString *element in array2) {
        NSLog(@"%@", element);
    }
 
   } 
    return 0;
 
}

4.5 Array of Integers

In the next example we will initialize an array of integers and then will iterate through it to display its values:

#import <Foundation/Foundation.h>
 
int main(int argc, const char * argv[])
{
 
  @autoreleasepool {
 
      NSInteger i, valElement, arraySize = 11;
      NSMutableArray *intArray = [NSMutableArray array];
 
      // initialize array with numbers from 1 to 10
      for ( i = 1; i < arraySize; i++) {
          [intArray insertObject:[NSNumber numberWithInteger:i] atIndex:i-1];
          valElement = [[intArray objectAtIndex:i-1] integerValue];
      }
 
    for (NSString *element in intArray) {
        NSLog(@"%@", element);
    }
 
   } 
    return 0;
 
}

Then we can modify previous code to delete last 4 elements of the array:

#import <Foundation/Foundation.h>
 
int main(int argc, const char * argv[])
{
 
  @autoreleasepool {
 
      NSInteger i, j, valElement, arraySize = 11;
      NSMutableArray *intArray = [NSMutableArray array];
 
      // initialize array with numbers from 1 to 10
      for ( i = 1; i < arraySize; i++) {
          [intArray insertObject:[NSNumber numberWithInteger:i] atIndex:i-1];
          valElement = [[intArray objectAtIndex:i-1] integerValue];
      }
 
      // will remove last 4 objects
      for (j = 1; j < 5; j++) {
          [intArray removeLastObject];
      }
 
      for (NSString *element in intArray) {
          NSLog(@"%@", element);
      }
 
   }
    return 0;
 
}

This concludes our first tutorial on Objective C. I hope you’ve like it and you’ve found it useful.

Read more from Objective C

Leave a Reply

required
required

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments