1.23. Allocating and Making Use of Arrays
Problem
You want to store a series of objects into another object for later use.
Solution
Use NSArray and NSMutableArray classes to store objects into
arrays that are fixed and that you can change, respectively.
Discussion
An object of type NSArray or
any of its subclasses has the capability to store
n number of other objects. These objects can then
be accessed using their index. For instance, let’s say you have 10
pairs of socks. Now imagine placing them all on a flat surface from
left to right and calling them socks 1, socks 2, socks 3, etc. So the
leftmost sock is now addressed as socks 1, the one next to it is
called socks 2, and so on. Isn’t that easier than saying something
like “the blue socks next to my red socks”? That’s exactly what arrays
do: they make arranging items much easier.
Note
You can place any object of type NSObject or any of its
subclasses into an array of type (or subclasses of) NSArray.
The primary difference between NSArray and NSMutableArray is that a mutable array can be
changed/modified after it has been allocated and initialized, whereas
an immutable array, NSArray, cannot.
Let’s have a look at an example. Let’s create an instance of
NSString and two instances of
NSNumber and place them in an
immutable array:
NSString *stringObject = @"My String"; NSNumber *signedNumber = [NSNumber numberWithInteger:-123]; NSNumber *unsignedNumber = [NSNumber numberWithUnsignedInteger:123]; NSArray *array = [[NSArray alloc] initWithObjects: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access