4

Objective-C noob here.

Why would this:

NSString *myString = [NSString alloc];
[myString initWithFormat:@"%f", storedNumber];  

results in the following exception -length only defined for abstract class. Define -[NSPlaceholderString length]!

When this works just fine:

NSString *myString = [[NSString alloc] initWithFormat:@"%f", storedNumber];

I would think that the latter is merely a contraction of the former (but I'm obviously wrong, at least according to the compiler).

2 Answers 2

4

Because -initWithFormat: is returning an object that’s different from the one returned by +alloc, i.e., an object that’s different from the one pointed by myString. That’s the reason why you should always couple +alloc with -init….

This situation is common in class clusters such as NSString. +alloc returns a generic string object, then -initWithFormat: decides upon a concrete subclass of NSString, deallocates the current object created by +alloc, creates a new object from a concrete subclass of NSString, and then returns this new object.

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

Comments

0
NSString *myString = [[NSString alloc] init];

or

NSString *myString = [NSString 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.