Why are these two NSString pointers the same?

2020-02-12 04:51发布

When I alloc and init two NSString variables and compare their pointers, they are the same. Here's a snippet that shows this:

NSString *s1 = [[NSString alloc] initWithString:@"hello world"];
NSString *s2 = [[NSString alloc] initWithString:@"hello world"];

if (s1 == s2) {
    NSLog(@"==");
}else {
    NSLog(@"!=");
}

Why are s1 and s2 the same?

2条回答
放荡不羁爱自由
2楼-- · 2020-02-12 05:15

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.

查看更多
\"骚年 ilove
3楼-- · 2020-02-12 05:27

@"hello world" strings are of class NSConstantString.if you use @"hello world" in two places, they will be referencing the very same object.

From documentation.

The simplest way to create a string object in source code is to use the Objective-C @"..." construct:

NSString *temp = @"/tmp/scratch"; Note that, when creating a string constant in this fashion, you should use UTF-8 characters. Such an object is created at compile time and exists throughout your program’s execution. The compiler makes such object constants unique on a per-module basis, and they’re never deallocated, though you can retain and release them as you do any other object. You can also send messages directly to a string constant as you do any other string:

BOOL same = [@"comparison" isEqualToString:myString];

查看更多
登录 后发表回答