O'Reilly logo

Objective-C Pocket Reference by Andrew Duncan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Object Lifecycle

Your classes will have methods that distinguish them from other classes and make them useful, but all classes must implement methods that manage their lifecycle—allocation, initialization, copying, and deletion. In addition, you will use library classes that come supplied with these methods, which you need to use in a consistent way. This section describes the design patterns that Objective-C programmers use and that library classes support.

The root classes Object and NSObject provide the following methods for managing the lifecycles of objects:

+initialize
+alloc
+new
-init
-copy
-dealloc

In addition, Object also provides these methods:

-shallowCopy
-deepCopy
-deepen
-free

In addition to these methods, many classes will provide more methods for initializing newly allocated objects.

Section 1.10 describes how these methods behave for the root classes; this section gives you guidelines on how to actually use the methods in your programs.

In managing the lifecycle of an object, you are faced with two issues: how to call these methods and how to write them for your own classes. Each of the following sections will first discuss how to call the methods, and then how to write them.

Creating an Object

Objective-C separates object creation into two steps: allocating memory and initializing fields. Allocation returns a pointer to cleared memory where the object will be stored. Initializing an object means setting its fields to some values, either default or specified. These operations ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required