2

It is my understanding that, in addition to allocating memory, alloc sets all instance variables (with the exception of the isa variable) to zero or to the equivalent type for zero, such as nil, NULL, and 0.0.

But I recently read the following about init:

Initialization sets the instance variables of an object to reasonable and useful initial values.

I'm a bit confused as to what "reasonable and useful initial values" means....

If alloc has already set the values to zero, is init altering these values in any way?

2 Answers 2

3

If alloc has already set the values to zero, is init altering these values in any way?

Sure.

For example, you may have an object that represents a rectangle with ivars to represent width and height; in init you may initialize these ivars to some sane default, say 300x200.

That's all they're talking about.

If you're asking whether NSObject's -init method is initializing the values of your subclass's ivars to some non-zero values, the answer of course is no.

Sign up to request clarification or add additional context in comments.

1 Comment

So the quote that I read was referring to convenience initializers and not NSObject's -init. That's exactly what I wanted to know...Thanks!
0

Yes, it is entirely possible. For example, a data structure may have member variables that require dynamic memory be allocated and initialized as well. The alloc call will reserve the space for the member variables and the init call will make those values useful (e.g., suballocation & initialization).

alloc and init are separate because you can have multiple init routines for a class that initialize an object in differing ways.

You can also call alloc and init at the same time by calling new. Thus the following two lines are equivalent:

[[NSObject alloc] init];
[NSObject new];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.