Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Not all objects can be meaningfully copied. If an object encapsulates a unique or scarce resource, it doesn’t make sense to copy the object. For example, Cocoa’s NSHost class encapsulates information about the unique network names and Internet addresses of a computer. It doesn’t make sense to copy an NSHost instance because doing so would duplicate the network names and Internet addresses that are supposed to be unique. The NSApplication class encapsulates a connection to Mac OS X’s Quartz window server so that Cocoa applications can draw windows on the screen. Each Cocoa application is permitted exactly one connection to the window server. For that reason, NSApplication uses the Singleton pattern introduced in Chapter 13, “Singleton.” It makes no sense to copy an instance of NSApplication because only one instance is permitted in each program.
When copying is supported, consider whether the copy operation is shallow or deep. A shallow copy is a copy of the object itself, but not any objects contained by the object being copied. In other words, when an object is shallow copied, the result is a new object that contains pointers to the exact same objects contained by the first. A deep copy copies the contained objects as well. The result of a deep copy is a new object that contains pointers to copies of the objects contained by the original. Usually, deep copies are as deep as possible. Objects within objects within objects are also copied to as deep a level as necessary to copy every object in the containment hierarchy.