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, where
n will be determined by the runtime and is
influenced by how much memory is available at the time. 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, and so on. So
the leftmost pair of socks is now addressed as socks 1, the pair next to
it is called socks 2, and the rightmost pair is called socks 10. 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 NSArray (or subclasses of that type). An
array can contain a mix of different types of objects. Not all objects
have to be of the same type. In other words, you can have one array
with strings, numbers, dictionaries, or even other arrays inside it.
Arrays can contain any object as long as those objects can be wrapped
in the id data type wrapper.
The primary difference between NSArray and NSMutableArray is that a mutable ...
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