Initializing Objects

You’ve seen the pattern before: You allocate a new instance of an object and then initialize it, using a familiar sequence like this:

Fraction *myFract = [[Fraction alloc] init];

We didn’t write our own init method here; we use the one we inherited from the parent class, which is NSObject.

After these two methods are invoked, you typically assign some values to the new object, like this:

[myFract setTo: 1 over: 3];

The process of initializing an object followed by setting it to some initial values is often combined into a single method. For example, you can define an initWith:over: method that initializes a fraction and sets its numerator and denominator to the two supplied arguments.

A class that contains many methods and ...

Get Programming in Objective-C, Fifth 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.