Difference between these two NSString methods

前端 未结 5 1362
广开言路
广开言路 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:53

    The correct answer is that

    NSString *someString = [NSString string];
    

    gives you an empty string that you do not own and that you must not release (according to the memory management rules)

    whereas

    NSString *someString = [[NSString alloc] init];
    

    gives you an empty string you do own and that you must release (according to the memory management rules).

    Without poking into the implementation, you can't say anything else about those two strings. You can't say that they are autoreleased, because they might not be and you can't say what the retain count will be.

    In actual fact, you'll probably get (in both cases) the same pointer to a constant object of some NSString subclass, probably with a retain count of UINT_MAX which is used by the run time as a flag to disable normal retain release behaviour for constant strings. I haven't actually tried the above because nobody except the maintainers of the Objective-C SDK needs to care.

提交回复
热议问题