Initializing NSString

Objective-C noob here.

Why is this:

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

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

When it works very well:

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

I would think that the latter is simply a shorthand for the former (but I am obviously mistaken, at least according to the compiler).

+4
source share
2 answers

Because -initWithFormat: returns an object different from the one returned by +alloc , i.e. an object different from the one pointed to by myString . This is why you should always combine +alloc with -init…

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

+4
source
 NSString *myString = [[NSString alloc] init]; 

or

 NSString *myString = [NSString new]; 
0
source

All Articles