There are three things going on here:
Firstly, the two identical string literals you're passing in to initWithString:
will have the same address to start. This is an obvious optimization for constant data.
Secondly, when you nest alloc and init with strings, the runtime performs an optimization, the alloc call essentially becomes a no-op. This is done using the NSPlaceholderString
class. This means the pointer you get back here will be coming from initWithString:
, not from alloc.
Thirdly, under the hood, initWithString:
is calling CFStringCreateCopy
, which as you may find, has the following behavior: Since this routine is for creating immutable strings, it has an optimization. It simply calls CFRetain()
and returns the same object that was passed in.
Thanks for the very interesting question. I had fun figuring it out.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…