articles

Home / DeveloperSection / Articles / Objective-C : Arrays

Objective-C : Arrays

Tarun Kumar3972 09-Jul-2015

Previously we learn how to define numbers type with NSNumber : Objective-C : Numbers

 

Objective-C programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

 

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.

 

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.


Objective-C : Arrays

 


Declaring Arrays


To declare an array in Objective-C, a programmer specifies the type of the elements and the number of elements required by an array as follows:

type arrayName [arraySize ];


This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid Objective-C data type. For example, to declare a 10-element array called balance of type double, use this statement:


double balance[10];

Now, balance is a variable array, which is sufficient to hold up to 10 double numbers.

 

Initializing Arrays


You can initialize an array in Objective-C either one by one or using a single statement as follows:

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array:

If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write:

double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};

 

You will create exactly the same array as you did in the previous example.

balance[4] = 50.0;

 

The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th, i.e., last element because all arrays have 0 as the index of their first element which is also called base index. Following is the pictorial representation of the same array we discussed above:


Objective-C : Arrays

 

Accessing Array Elements


An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example:

double salary = balance[9]; 

The above statement will take 10th element from the array and assign the value to salary variable.

 

Finding out the Number of Elements in an Array


The number of objects in an array (referred to as elements) can be identified using the count instance method of the NSArray class:

#import <Foundation/Foundation.h>
int main ()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   
    NSArray *myColors;     
    myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
    NSLog (@"Number of elements in array = %lu", [myColors count]);
   
    [pool drain];
    return 0;
}

When executed, the above code will be displayed:

2015-07-10 02:35:11.472 demo[27440] Number of elements in array = 4


Accessing the Elements of an Array Object


The objects contained in an array are given index positions beginning at position zero. Each element may be accessed by passing the required index position through as an argument to the NSArray objectAtIndex instance method. We can, therefore, now extend our array example to display each element, using the count method to identify in advance how many elements there are to display: 

#import <Foundation/Foundation.h> int main () { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSArray *myColors; int i; int count; myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil]; count = [myColors count]; for (i = 0; i < count; i++) NSLog (@"Element %i = %@", i, [myColors objectAtIndex: i]); [pool drain]; return 0; }

When run, the above code will display each element in the array object:

2015-07-10 02:42:42.667 demo[32249] Element 0 = Red
2015-07-10 02:42:42.668 demo[32249] Element 1 = Green
2015-07-10 02:42:42.668 demo[32249] Element 2 = Blue
2015-07-10 02:42:42.668 demo[32249] Element 3 = Yellow

 

Accessing Array Elements using Fast Enumeration


The technique for accessing all the array elements using a for loop as described in the previous section is a little ungainly. Another, easier mechanism for accessing element in an array involves something called fast enumeration. Fast enumeration simply requires that a variable be declared to hold each array element, and then referenced in the for loop:

#import <Foundation/Foundation.h>
int main ()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   
    NSArray *myColors;
    NSString *color;
    myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
    for (color in myColors)
        NSLog (@"Element = %@", color);

    [pool drain];
    return 0;
}

When run, the above code will display each element in the array object:

2015-07-10 02:50:21.1000 demo[3758] Element = Red
2015-07-10 02:50:22.001 demo[3758] Element = Green
2015-07-10 02:50:22.001 demo[3758] Element = Blue
2015-07-10 02:50:22.001 demo[3758] Element = Yellow

 

Adding Elements to an Array Object


New elements may be added to a mutable array object using the addObject instance method of the NSMutableArray class. For example, to declare and initialize an array, and then later add new element object the following code might be used:

#import <Foundation/Foundation.h> int main () { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSMutableArray *myColors; NSString *color; myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil]; //Before Adding Elements for (color in myColors) NSLog (@"Before Adding Element = %@", color); [myColors addObject: @"Indigo"]; [myColors addObject: @"Violet"]; //After Adding Elements for (color in myColors) NSLog (@"After Adding Element = %@", color); [pool drain]; return 0; }

When run, the above code will display each element in the array object:

2015-07-10 03:02:43.767 demo[9598] Before Adding Element = Red
2015-07-10 03:02:43.768 demo[9598] Before Adding Element = Green
2015-07-10 03:02:43.768 demo[9598] Before Adding Element = Blue
2015-07-10 03:02:43.768 demo[9598] Before Adding Element = Yellow
2015-07-10 03:02:43.768 demo[9598] After Adding Element = Red 2015-07-10 03:02:43.768 demo[9598] After Adding Element = Green
2015-07-10 03:02:43.768 demo[9598] After Adding Element = Indigo
2015-07-10 03:02:43.768 demo[9598] After Adding Element = Blue 2015-07-10 03:02:43.768 demo[9598] After Adding Element = Yellow
2015-07-10 03:02:43.768 demo[9598] After Adding Element = Violet

 

Inserting Elements into an Array


The previous method appends new objects onto the end of an array. It is also possible to insert new objects at specific index points in an array object using the insertObject instance method. This method accepts as arguments the object to be inserted and the index position at which the insertion is to take place:

#import <Foundation/Foundation.h>
int main ()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   
    NSMutableArray *myColors;
    int i;
    int count;
    myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
    [myColors insertObject: @"Indigo" atIndex: 1];
    [myColors insertObject: @"Violet" atIndex: 3];
    count = [myColors count];
    for (i = 0; i < count; i++)
        NSLog (@"Element %i = %@", i, [myColors objectAtIndex: i]);

    [pool drain];
    return 0;
}

When we compile and run the code, the output will be like this:

2015-07-10 03:04:17.131 demo[10617] Element 0 = Red
2015-07-10 03:04:17.132 demo[10617] Element 1 = Indigo
2015-07-10 03:04:17.132 demo[10617] Element 2 = Green
2015-07-10 03:04:17.132 demo[10617] Element 4 = Blue
2015-07-10 03:04:17.132 demo[10617] Element 3 = Violet
2015-07-10 03:04:17.132 demo[10617] Element 5 = Yellow

 

Deleting Elements from an Array Object


The NSMutableArray class provides a number of instance methods designed specifically to remove one or more elements from an array object. A sample of some of the more commonly used methods is provided below. This list is not exhaustive so refer to the Foundation Framework documentation for the NSMutableArray class for a full listing.

To remove an element at a specific index location, use the removeObjectAtIndex method and

To remove the first instance of a specific object from an array use removeObject:
#import <Foundation/Foundation.h>
int main ()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];   
    NSMutableArray *myColors;
    int i, count;
    myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
    [myColors removeObject: @"Yellow"];
    [myColors removeObjectAtIndex: 0];
    count = [myColors count];
    for(i=0; i<count; i++)
        NSLog(@"Element %@", [myColors objectAtIndex:i]);
       
    [pool drain];
    return 0;
}

When run, the above code will display each element in the array object:

2015-07-10 03:27:55.696 demo[23220] Element Green
2015-07-10 03:27:55.697 demo[23220] Element Blue
 
To remove all instances of a specific object in an array, use

removeObjectIdenticalTo:

#import <Foundation/Foundation.h>
int main ()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];   
    NSMutableArray *myColors;
    int i, count;
    myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", @"Red", @"Red", nil];
    [myColors removeObjectIdenticalTo: @"Red"];

    count = [myColors count];
    for(i=0; i<count; i++)
        NSLog(@"Element %@", [myColors objectAtIndex:i]);
       
    [pool drain];
    return 0;
}

When run, the above code will display each element in the array object:

2015-07-10 03:33:20.194 demo[26580] Element Green
2015-07-10 03:33:20.196 demo[26580] Element Blue
2015-07-10 03:33:20.196 demo[26580] Element Yellow

 

To remove all objects from an array, use removeAllObjects:

 myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
[myColors removeAllObjects];
To remove the last object in the array, use the removeLastObject method:


myColors = [NSMutableArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];
 [myColors removeLastObject];
Sorting Array Objects


The Foundation Framework NSArray class, and the subclasses thereof, provide a number of mechanisms for sorting the elements of an array into a specific order. The simplest way to achieve this is to use the sortedArrayUsingSelector instance method. For example, to perform a sort on our example array using this method, we could use the following code:

#import <Foundation/Foundation.h>
int main ()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];    
    int i, count;
    NSMutableArray *myColors = [NSMutableArray arrayWithObjects: @"red", @"green", @"blue", @"yellow", nil];
    NSArray *sortedArray;
    sortedArray = [myColors sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

    count = [sortedArray count];
    for(i=0; i<count; i++)
        NSLog(@"Element %@", [sortedArray objectAtIndex:i]);
        
    [pool drain];
    return 0;
}

When run, the above code will display each element in the array object in sorted way:

2015-07-10 03:45:53.524 demo[32666] Element blue
2015-07-10 03:45:53.525 demo[32666] Element green
2015-07-10 03:45:53.525 demo[32666] Element red
2015-07-10 03:45:53.525 demo[32666] Element yellow

As we can see from the above example, the method returns a new array containing the elements of the original array sorted using the localizedCaseInsensitiveCompare method. In practice any method can be used in this context as long as that method is able to compare two objects and return an NSOrderedAscending, NSOrderedSame or NSOrderedDescending result.



Next, we will learn about: Objective-C : Strings


Updated 07-Sep-2019

Leave Comment

Comments

Liked By