Objective-C Language Subscripts with NSArray


Example

Subscripts can be used to simplify retrieving and setting elements in an array. Given the following array

NSArray *fruit = @[@"Apples", @"Bananas", @"Cherries"];

This line

[fruit objectAtIndex: 1];

Can be replaced by

fruit[1];

They can also be used to set an element in a mutable array.

NSMutableArray *fruit = [@[@"Apples", @"Bananas", @"Cherries"] mutableCopy];
fruit[1] = @"Blueberries";
NSLog(@"%@", fruit[1]); //Blueberries

If the index of the subscript equals the count of the array, the element will be appended to the array.

Repeated subscripts may be used to access elements of nested arrays.

NSArray *fruit = @[@"Apples", @"Bananas", @"Cherries"];
NSArray *vegetables = @[@"Avocado", @"Beans", @"Carrots"];
NSArray *produce = @[fruit, vegetables];
    
NSLog(@"%@", produce[0][1]); //Bananas