In this chapter, you’ll learn how memory is managed in iOS and the concepts that underlie automatic reference counting, or ARC. We’ll start with some basics of application memory.
All Objective-C objects are stored in a part of memory called the heap. When we send an alloc message to a class, a chunk of memory is allocated from the heap. This chunk includes space for the object’s instance variables.
For example, consider an instance of NSDate, which represents a specific point in time. An NSDate has two instance variables: a double that stores the number of seconds since a fixed reference point in time and the isa pointer, which every object inherits from NSObject. A double is eight bytes, and a pointer is 4 bytes, so each time alloc is sent to the NSDate class, 12 bytes is allocated from the heap for a new NSDate object.
Consider another example: BNRItem. A BNRItem has five instance variables: four pointers (isa, itemName, serialNumber, and dateCreated) and an int (valueInDollars). The amount of memory needed for an int is four bytes, so the total size of a BNRItem is 20 bytes (Figure 3.1).
Figure 3.1 Byte count of BNRItem and NSDate instances
Notice in Figure 3.1 that the NSDate object does not live inside the BNRItem. Objects never live inside one another; they exist separately on the heap. Instead, objects keep references to other objects as needed. These references are the pointer instance variables of an object. Thus, when a BNRItem’s dateCreated instance variable is set, the address of the NSDate instance is stored in the BNRItem, not the NSDate itself. So, if the NSDate was 10, 20, or even 1000 bytes, it wouldn’t affect the size of the BNRItem.)