Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between these two NSString methods

So I just got asked this at an interview today and after some googling am still unable to figure out the answer (in fact I couldn't even find any code at all which used the [NSString string] method).

What is the difference between

  1. NSString *someString = [NSString string];
  2. NSString *someString = [[NSString alloc] init];

Now my initial thoughts were that [NSString string] would return an object which would be autoreleased whereas using alloc and init would return an object which has been retained. However it seems that this answer was incorrect.

I've looked at the NSString class reference in the apple docs but all it says is

Returns an empty string.

+ (id)string 

Return Value
An empty string.

Could somebody explain to me exactly what the difference between these two are?

like image 436
Jason Avatar asked Oct 26 '11 08:10

Jason


1 Answers

Was that your response, and did you ask why your answer was incorrect? I ask because your assumption is mostly correct (at a higher level).

It's not exactly 'retained' when returned from alloc+init, it is an object you hold one reference to, and should balance with a release or autorelease. For the convenience constructor (+[NSString string]), you are returned an object which you hold zero references to, but one which you can expect to live until the current autorelease pool is popped unless you send it an explicit retain (assuming MRC or ARC, since it is tagged iOS).

At the lower level, you could make some guesses, but I wouldn't expect that question in many objc interviews (unless you told them you were mid or senior level). Basically, it is implementation defined, but both forms could return the same static, constant NSString (that may have been what the interviewer was looking for). To illustrate:

@implementation NSString

static NSString * const EmptyNSString = @"";

- (id)init
{
    self = [super init];
    [self release];
    return EmptyNSString;
}

+ (id)string
{
    return EmptyNSString;
}

...

Again, that's implementation defined, but an obvious optimization. As well, that optimization makes physically subclassing concrete immutable types (NSString) difficult for mutable variants (NSMutableString) in some cases.

like image 139
justin Avatar answered Nov 07 '22 05:11

justin