1.15. Allocating and Initializing Objects
Problem
You want to create an instance of a new object, but you don’t understand the difference between allocation and initialization and why you should have to both allocate and initialize an object before you can use it.
Solution
You must both allocate and initialize an object before using it.
An object can be allocated using the alloc instance method. This class method will
allocate memory to hold the object and its instance variables and
methods. However, allocation leaves memory undefined. So in addition,
each object must be initialized, which sets the
values of its data. One initialization method must be the
designated initializer, which is normally the
initialization method with the most parameters. For instance, the
initWithFrame: method is the
designated initializer of objects of type UIView. Always allocate and initialize your
objects, in that order, before using them.
When implementing a new object, do not override the alloc method. This method is declared in
NSObject. Instead, override the
init method and create custom
initialization methods that handle required parameters for the specific
object you are working on.
Discussion
An object that inherits from NSObject must be prepared for use in two
steps:
- Allocation
The allocation is done by invoking the
allocmethod, which is implemented in theNSObjectclass. This method creates the internal structure of a new object and sets all instance variables’ values to zero. After this step is ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access