为什么这两个NSString指针相同? [英] Why are these two NSString pointers the same?

查看:172
本文介绍了为什么这两个NSString指针相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当I alloc init 两个 NSString 变量并比较他们的指针,他们是一样的。这里是一个片断显示这:

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(@"!=");
}

为什么 s1 s2 相同?

推荐答案

首先,传入 initWithString:的两个相同的字符串文字将具有相同的地址开始。这是对常量数据的一个明显的优化。

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.

其次,当你使用字符串嵌套alloc和init时,运行时执行优化,alloc调用基本上变成无操作。这是使用 NSPlaceholderString 类完成的。这意味着你返回的指针将来自 initWithString:,而不是来自alloc。

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.

引擎盖, initWithString:正在调用 CFStringCreateCopy ,你可能会发现,具有以下行为:因为这个例程是为了创建不可变的字符串,它有一个优化。它只需调用 CFRetain(),并返回传入的相同对象。

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.

这篇关于为什么这两个NSString指针相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆