Chapter 3. Collections

As a Cocoa developer, you are provided with many classes that can help you group several of your objects together in specific ways. This chapter discusses the main collection classes available to you.

Section 3.1 addresses the topic of arrays. You learn about immutable and mutable arrays, the different approaches used for copying arrays, and several sorting techniques. Section 3.2 covers the topic of sets. Sets are collections that do not impose ordering on the objects they contain. You learn about immutable and mutable sets as well as several interesting operations on sets. Section 3.3 discusses dictionaries. Dictionaries allow you to store objects and retrieve them using keys. As you saw in Section 2.7, dictionaries are widely used in Cocoa frameworks and understanding them is essential. Finally, we provide a summary in Section 3.4.

Arrays

You use NSArray and NSMutableArray if you would like to store/access your objects in an ordered way. NSArray is the immutable version of the array, allowing you to store your objects only once (during initialization). NSMutableArray is a subclass of NSArray that allows you to add/remove objects even after initialization of the collection.

To help illustrate the main concepts behind arrays, let us use the simple class Person shown in Listing 3.1.

Example 3.1. The class Person used in the arrays examples.

#import <Foundation/Foundation.h>
@interface Person : NSObject{
  NSString *name;
  NSString *address; } @property(copy) NSString ...

Get iPhone SDK 3 Programming: Advanced Mobile Development for Apple iPhone and iPod touch now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.