Title here
Summary here
Our first example demonstrates how to work with arrays in Objective-C. Arrays are ordered collections of elements of a specific type.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// Here we create an NSMutableArray 'a' that will hold NSNumber objects.
// By default, the array is empty.
NSMutableArray *a = [NSMutableArray arrayWithCapacity:5];
for (int i = 0; i < 5; i++) {
[a addObject:@0];
}
NSLog(@"emp: %@", a);
// We can set a value at an index using the setObject:atIndex: method,
// and get a value with objectAtIndex:.
[a setObject:@100 atIndex:4];
NSLog(@"set: %@", a);
NSLog(@"get: %@", [a objectAtIndex:4]);
// The count method returns the length of an array.
NSLog(@"len: %lu", (unsigned long)[a count]);
// Use this syntax to declare and initialize an array in one line.
NSArray *b = @[@1, @2, @3, @4, @5];
NSLog(@"dcl: %@", b);
// In Objective-C, we can't directly create an array with a specific size and initial values.
// However, we can create an array with repeated values like this:
NSArray *c = [@[@100, @0, @0, @400, @500] mutableCopy];
NSLog(@"idx: %@", c);
// Array types are one-dimensional, but you can compose types to build multi-dimensional data structures.
NSMutableArray *twoD = [NSMutableArray array];
for (int i = 0; i < 2; i++) {
NSMutableArray *row = [NSMutableArray array];
for (int j = 0; j < 3; j++) {
[row addObject:@(i + j)];
}
[twoD addObject:row];
}
NSLog(@"2d: %@", twoD);
// You can create and initialize multi-dimensional arrays at once too.
NSArray *twoD2 = @[
@[@1, @2, @3],
@[@1, @2, @3]
];
NSLog(@"2d: %@", twoD2);
}
return 0;
}
When you run this program, you’ll see output similar to:
emp: (0, 0, 0, 0, 0)
set: (0, 0, 0, 0, 100)
get: 100
len: 5
dcl: (1, 2, 3, 4, 5)
idx: (100, 0, 0, 400, 500)
2d: ((0, 1, 2), (1, 2, 3))
2d: ((1, 2, 3), (1, 2, 3))
Note that arrays in Objective-C are actually objects (instances of NSArray
or NSMutableArray
), and they can only contain objects. For primitive types like int
, we wrap them in NSNumber
objects.
Also, Objective-C arrays are zero-indexed, meaning the first element is at index 0.
Objective-C provides two main types of arrays:
NSArray
: An immutable array that can’t be changed after creation.NSMutableArray
: A mutable array that can be modified after creation.In this example, we’ve used both types to demonstrate different array operations.