为什么要取消引用的NSString指针是没有必要? [英] Why dereferencing a NSString pointer is not necessary?

查看:178
本文介绍了为什么要取消引用的NSString指针是没有必要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个例子

NSString *message = @"Hello";
message = @"World";

如果消息只是一个指针,为什么不让我需要明确地说,无论是在消息现在等于字符串或 *消息= @世界; 像用C?

If message is just a pointer why don't I need to explicitly say whatever is in message is now equal to string or *message = @"World"; like in C?

推荐答案

免责声明

下面的讨论给出为什么你从​​来没有dereferenciate指针在Objective-C的对象的总体思路。
然而,有关的的NSString 文本的特定情况下,这不是什么发生在现实中。虽然下面描述的结构仍然是健全的,它可能工作方式,什么是实际发生的是,对于一个字符串的空间在编​​译时分配的,你会得到它的地址返回给用户。这是一个字符串如此,因为它们是不变的常数。出于效率的考虑,因此每个文字被分配一次。

The discussion below gives a general idea on why you never dereferenciate a pointer to an object in Objective-C. However, concerning the specific case of NSString literals, this is not what's happening in reality. While the structure described below is still sound and it may work that way, what's actually happening is that the space for a string literal is allocated at compile time, and you get its address back. This is true for string literals, since they are immutable and constant. For the sake of efficiency therefore each literal is allocated only once.

作为事实上

NSString * a = @"Hello";
NSString * b = @"Hello";
NSLog(@"%@ %p", a, a); // Hello 0x1f4958
NSLog(@"%@ %p", b, b); // Hello 0x1f4958


原来的答案

由于它会被翻译成

message = [[NSString alloc] initWithUTF8String:"Hello"]];

这将归结为

message = objc_msgSend(objc_msgSend(objc_getClass("NSString"), @selector(alloc)), @selector(initWithUTF8String:), "Hello");

现在,如果我们看一看,以 objc_msgSend

Now if we take a look to the signature of objc_msgSend

id objc_msgSend(id theReceiver, SEL theSelector, ...)

我们可以看到,该方法返回一个 ID 类型,在Objective-C是对象类型。但是,如何为 ID 实际上界定?

we see that the method returns an id type, which in Objective-C is the object type. But how is id actually defined?

typedef struct objc_object {
    Class isa;
} *id;

ID 被定义为一个指向 objc_object 结构。

id is defined as a pointer to an objc_object struct.

那么,到底 @串将在函数调用,将产生一个指向一个对象(即一个 objc_object 结构,如果preFER),而这正是你需要分配给的消息什么

So in the end @"string" will translate in a function call that will produce a pointer to an object (i.e. an objc_object struct, if you prefer), which is exactly what you need to assign to message.

底线,您指定的指针,而不是对象

要更好地澄清过去的观念考虑这个

To better clarify the last concept consider this

NSMutableString * a = [NSMutableString stringWithString:@"hello"];
NSMutableString * b = a;
[a setString:@"hola"];
NSLog(@"%@", a); // "hola"
NSLog(@"%@", b); // "hola"

如果你指定的对象, B 本来的副本 A 和<$的任何进一步的修改C $ C> A 不会影响 b

If you were assigning objects, b would have been a copy of a and any further modification of a wouldn't have affected b.

相反,你得到的是 A B 是两个指针堆中相同的对象。

Instead what you get is a and b being two pointers to the same object in the heap.

这篇关于为什么要取消引用的NSString指针是没有必要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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