Objective C Tutorial - Objective C Arrays






Array is a data structure to store a fixed-size sequential collection of elements of the same type.

Declaring Arrays

To declare an array in Objective-C, we use the following syntax.

type arrayName [ arraySize ];

type defines the data type of the array elements. type can be any valid Objective-C data type.

arraySize sets the element count inside the array. arraySize must be an integer constant greater than zero

The following line of code defines a 10-element array called myArray of type double.

double myArray[10];




Initializing Arrays

We can initialize an array using a single statement as follows:

double myArray[5] = {1.0, 2.0, 3.4, 12.0, 52.0};

The number of values in { } can not be larger than the number of elements that we declare in [].

We can omit the size of the array and the compiler will create an array just big enough to hold the initialization.

double myArray[] = {1.0, 2.0, 3.4, 11.0, 23.0};

Array element index starts from 0, the following line sets the value for the fifth element.

myArray[4] = 5.0;




Example

#import <Foundation/Foundation.h>
 
int main ()
{
   int n[ 10 ];
   int i,j;
       
   for ( i = 0; i < 10; i++ )
   {
      n[ i ] = i + 100; /* set element at location i to i + 100 */
   }
   
   for (j = 0; j < 10; j++ )
   {
      NSLog(@"Element[%d] = %d\n", j, n[j] );
   }
 
   return 0;
}

Creating an Array


#import <Foundation/Foundation.h>
 
int main ()
{
  NSString *object1 = @"Hello";
    NSString *object2 = @"world!";
    NSNumber *object3 = [NSNumber numberWithInt:45];
    NSArray *myArray;
    myArray= [NSArray arrayWithObjects: object1, object2, object3, nil];
    NSLog(@"Array contents = %@",[myArray componentsJoinedByString:@", "]);  
 
   return 0;
}

The code above generates the following result.

Accessing All Items in an Array


#import <Foundation/Foundation.h>
 
int main ()
{
  NSString *object1 = @"Hello";
    NSString *object2 = @"world!";
    NSString *object3 = @"Good-bye";
    NSArray *myArray;
    myArray= [NSArray arrayWithObjects: object1, object2, object3, nil];
    for (NSString *randomVariable in myArray) 
    {
    NSLog (@"Array element = %@", randomVariable);
    }  
 
   return 0;
}

The code above generates the following result.

Accessing All Items in an Array for loop

#import <Foundation/Foundation.h>
 
int main ()
{
  NSString *object1 = @"Hello";
    NSString *object2 = @"world!";
    NSNumber *object3 = [NSNumber numberWithInt:45];
    NSArray *myArray;
    myArray= [NSArray arrayWithObjects: object1, object2, object3, nil];
    int i;
    for (i = 0; i < [myArray count]; i++)
    {
        NSLog (@"Element %i = %@", i, [myArray objectAtIndex: i]); 
    }
 
   return 0;
}

The code above generates the following result.

Accessing an Item in an Array


#import <Foundation/Foundation.h>
 
int main ()
{
  NSString *object1 = @"Hello";
    NSString *object2 = @"world!";
    NSNumber *object3 = [NSNumber numberWithInt:45];
    NSArray *myArray;
    myArray= [NSArray arrayWithObjects: object1, object2, object3, nil];
    NSLog(@"Array contents = %@",[myArray componentsJoinedByString:@", "]);
  NSLog (@"Index position 1 = %@", [myArray objectAtIndex:1]);  
 
   return 0;
}

The code above generates the following result.

Store Reference Objects to an Array

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
        NSMutableArray *listOfLetters = [NSMutableArray arrayWithObjects:@"A", @"B", @"C", nil];
        
        NSString *stringObject1 = [listOfLetters objectAtIndex:0];
        
        NSLog(@"stringObject1 = %@", stringObject1);
        
        NSString *stringObject2 = [listOfLetters lastObject];
        
        NSLog(@"stringObject2 = %@", stringObject2);
        
        NSUInteger position = [listOfLetters indexOfObject:@"B"];
        
        NSLog(@"position = %lu", position);
    return 0;
}

The code above generates the following result.

Adding Items to an Array

#import <Foundation/Foundation.h>
 
int main ()
{
  NSString *object1 = @"Hello";
    NSString *object2 = @"world!";
    NSString *object3 = @"Good-bye";
    NSMutableArray *myArray;
    myArray= [NSMutableArray arrayWithObjects: object1, object2, object3, nil];
    for (NSString *randomVariable in myArray) 
    {
    NSLog (@"Array element = %@", randomVariable);
    }
    [myArray addObject: @"New item"];
    NSLog (@"**********");
    for (NSString *randomVariable in myArray) 
    {
        NSLog (@"Array element = %@", randomVariable);
    }  
 
   return 0;
}

The code above generates the following result.

Counting Items Stored in an Array

#import <Foundation/Foundation.h>
 
int main ()
{
  NSString *object1 = @"Hello";
    NSString *object2 = @"world!";
    NSNumber *object3 = [NSNumber numberWithInt:45];
    NSArray *myArray;
    myArray= [NSArray arrayWithObjects: object1, object2, object3, nil];
    NSLog(@"Array contents = %@",[myArray componentsJoinedByString:@", "]);
    NSLog (@"Total number of items in array = %i", [myArray count]);  
 
   return 0;
}

The code above generates the following result.

Deleting All Instances of an Item From an Array

#import <Foundation/Foundation.h>
 
int main ()
{
  NSString *object1 = @"Hello";
    NSString *object2 = @"world!";
    NSString *object3 = @"Good-bye";
    NSString *object4 = @"Hello";
    NSString *object5 = @"More data";
    NSString *object6 = @"Hello";
    NSString *object7 = @"Last data";
    NSMutableArray *myArray;
    myArray= [NSMutableArray arrayWithObjects: object1, object2, object3, object4, object5, object6, object7, nil];
    NSLog (@"***** Original array *****");
    for (NSString *randomVariable in myArray) 
    {
    NSLog (@"Array element = %@", randomVariable);
    }
    
    NSLog (@"***** Deleting last array item *****");
    [myArray removeLastObject];
    for (NSString *randomVariable in myArray) 
    {
        NSLog (@"Array element = %@", randomVariable);
    }
    
    NSLog (@"***** Deleting item at index position 2 *****");
    [myArray removeObjectAtIndex: 2];
    for (NSString *randomVariable in myArray) 
    {
        NSLog (@"Array element = %@", randomVariable);
    }
  
    NSLog (@"***** Deleting all instances of Hello *****");
    [myArray removeObject: @"Hello"];
    for (NSString *randomVariable in myArray) 
    {
        NSLog (@"Array element = %@", randomVariable);
    }
 
   return 0;
}

The code above generates the following result.

Inserting Items in an Array

#import <Foundation/Foundation.h>
 
int main ()
{
  NSString *object1 = @"Hello";
    NSString *object2 = @"world!";
    NSString *object3 = @"Good-bye";//[NSNumber numberWithInt:45];
    NSMutableArray *myArray;
    myArray= [NSMutableArray arrayWithObjects: object1, object2, object3, nil];
    for (NSString *randomVariable in myArray) 
    {
    NSLog (@"Array element = %@", randomVariable);
    }
    [myArray insertObject: @"New item" atIndex: 1];
    NSLog (@"**********");
    for (NSString *randomVariable in myArray) 
    {
        NSLog (@"Array element = %@", randomVariable);
    }
 
   return 0;
}

The code above generates the following result.

Array Iteration

#import <Foundation/Foundation.h>

@interface Class1 : NSObject

-(void)reportState;

-(NSString *) doSomethingSpecial;

@end


@implementation Class1

-(void)reportState{
    NSLog(@"Class1 objects are reporting state: One");
}

-(NSString *) doSomethingSpecial{
    return @"Class One objects do something special";
}

@end


#import <Foundation/Foundation.h>

@interface Class2 : NSObject

-(void)reportState;


@end

@implementation Class2

-(void)reportState{
    NSLog(@"Class2 objects are reporting state: Two");
}

@end


int main (int argc, const char * argv[])
{
        
        NSMutableString *string1 = [NSMutableString stringWithString:@"A"];
        NSMutableString *string2 = [NSMutableString stringWithString:@"B"];
        NSMutableString *string3 = [NSMutableString stringWithString:@"C"];
        
        NSArray *listOfObjects = [NSArray arrayWithObjects:string1, string2, string3, nil];
        
        for(NSMutableString *s in listOfObjects){
            NSLog(@"This string in lowercase is %@", [s lowercaseString]);
        }
        
        [listOfObjects makeObjectsPerformSelector:@selector(appendString:)
                                       withObject:@"-MORE"];
        
        [listOfObjects enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSLog(@"object(%lu)'s description is %@",idx, [obj description]);
        }];
        
    
    return 0;
}

The code above generates the following result.

Save Array to a File


#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

        
        NSArray *listOfObjects = [NSArray arrayWithObjects:@"A", @"B", @"C", [NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3],  nil];
        
        NSString *filePathName = @"/Users/Shared/array.txt";
        
        [listOfObjects writeToFile:filePathName
                        atomically:YES];
        
    
    return 0;
}

Reading Arrays from a File

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

        NSString *filePathName = @"/Users/Shared/array.txt";
        
        NSArray *listOfObjects = [[NSArray alloc] initWithContentsOfFile:filePathName];
        
        NSLog(@"%@", listOfObjects);
        
    return 0;
}