Chapter 3. Foundation

Foundation is the underlying library that supports all Objective-C development. It provides basic support for data structures such as strings, arrays, dictionaries, and other generic objects, as well as methods for working with them.

Foundation operates at a lower level of abstraction in your application than the higher-level Cocoa libraries. While Cocoa and UIKit are concerned with applications, views, and user input, Foundation is concerned with the lower-level task of organizing data. In this chapter, you’ll work with several of the key classes that Foundation provides, and learn about the design patterns that Cocoa and Cocoa Touch are based on.

Mutable and Immutable Objects

Almost every data storage class in Foundation comes in two flavors: mutable and immutable. Mutable objects are objects that you can modify after creating them; immutable objects can’t be changed after they’re created.

As an example, let’s look at the NSArray class, which we’ll discuss in more detail later in this chapter. NSArray stores objects as a list, but you can’t add, remove, or replace objects in an existing NSArray because it’s immutable. If you want to be able to change the contents, you need to work with the NSMutableArray class, which does allow you to modify it.

Why do we have both immutable and mutable versions of an object? Two main reasons:

  1. If an object is immutable, it knows that it will never have to change the way it’s laid out in memory, and therefore is more efficient. ...

Get Learning Cocoa with Objective-C, 4th Edition 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.