21

I am wondering what differences such as disadvantages and/or advantages there are to declaring an NSString this way:

NSString *noInit = [NSString stringWithFormat:@"lolcatz %d", i];

as opposed to:

NSString *withInit = [[NSString alloc] initWithFormat:@"Hai %d", i];

What was the motivation of putting stringWithFormat instead of just having the initWithFormat way of initializing the string?

2 Answers 2

37

stringWithFormat: returns an autoreleased string; initWithFormat: returns a string that must be released by the caller. The former is a so-called "convenience" method that is useful for short-lived strings, so the caller doesn't have to remember to call release.

2
  • 1
    Beaten to the punch by 32 seconds. :-) Commented Oct 10, 2010 at 4:10
  • 2
    Actually; it is the +alloc that returns the retained instance... the init* doesn't change the retain count (but it may -- will, in this case -- return a different instance than was called).
    – bbum
    Commented Nov 29, 2011 at 20:45
5

I actually came across this blog entry on memory optimizations just yesterday. In it, the author gives specific reasons why he chooses to use [[NSString alloc] initWithFormat:@"..."] instead of [NSString stringWithFormat:@"..."]. Specifically, iOS devices may not auto-release the memory pool as soon as you would prefer if you create an autorelease object.

The former version requires that you manually release it, in a construct such as this:

NSString *remainingStr = nil;
if (remaining > 1)
    remainingStr = [[NSString alloc] initWithFormat:@"You have %d left to go!", remaining];
else if (remaining == 1)
    remainingStr = [[NSString alloc] initWithString:@"You have 1 left to go!"];
else
    remainingStr = [[NSString alloc] initWithString:@"You have them all!"];

NSString *msg = [NSString stringWithFormat:@"Level complete! %@", remainingStr];

[remainingStr release];

[self displayMessage:msg];

Here, remainingStr was only needed temporarily, and so to avoid the autorelease (which may happen MUCH later in the program), I explicitly handle the memory as I need it.

1
  • 1
    It a choice between premature optimization and clear concise code. Premature optimizations can be resolved later by analyzing the performance, unclear code is (usually) forever.
    – zaph
    Commented Dec 3, 2011 at 14:40

Your Answer

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