Difference between these two NSString methods

前端 未结 5 1384
广开言路
广开言路 2021-01-05 08:59

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

5条回答
  •  温柔的废话
    2021-01-05 09:52

    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.

提交回复
热议问题