NSString文字之间的区别 [英] Difference between NSString literals

查看:109
本文介绍了NSString文字之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两行之间有什么区别?

What is the difference between these two lines?

NSString * string = @"My String";
NSString * string = [[[NSString alloc] initWithString:@"MyString"] autorelease]


推荐答案

@My String是一个编译成二进制文件的文字字符串。加载时,它在内存中有一个地方。

@"My String" is a literal string compiled into the binary. When loaded, it has a place in memory. The first line declares a variable that points to that point in memory.

从字符串编程指南:


在源代码中创建字符串对象的最简单的方法是使用
Objective-C @...构造:

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



NSString *temp = @"/tmp/scratch"; 




注意,当创建一个字符串时
时尚,你应该避免使用任何东西,但7位
ASCII字符。这样的对象在编译时创建,并且在程序执行过程中存在
。编译器使这种对象
常量在每个模块基础上是唯一的,并且它们从不被释放,
虽然你可以像处理任何其他对象一样保留和释放它们。

Note that, when creating a string constant in this fashion, you should avoid using anything but 7-bit ASCII 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.

第二行通过获取该字符串来分配字符串。注意,@My String字符串都是相同的。要证明这一点:

The second line allocates a string by taking that literal string. Note that both @"My String" literal strings are the same. To prove this:

NSString *str = @"My String";
NSLog(@"%@ (%p)", str, str);

NSString *str2 = [[NSString alloc] initWithString:@"My String"];
NSLog(@"%@ (%p)", str2, str2);

NSString *copy = [str2 stringByAppendingString:@"2"];
NSLog(@"%@ (%p)", copy, copy);

输出相同的内存地址:

2011-11-07 07:11:26.172 Craplet[5433:707] My String (0x100002268)
2011-11-07 07:11:26.174 Craplet[5433:707] My String (0x100002268)
2011-11-07 07:11:26.174 Craplet[5433:707] My String2 (0x1003002a0)

什么告诉不仅前两个字符串是相同的内存地址,但如果你不更改代码,每次运行它是相同的内存地址。它是内存中相同的二进制偏移量。但是,不仅是副本不同,但它是不同的,每次你运行它,因为它分配在堆上。

What's telling is not only are the first two string the same memory address, but if you don't change the code, it's the same memory address every time you run it. It's the same binary offset in memory. But, not only is the copy different but it's different every time you run it since it's allocated on the heap.

根据上面的doc文档,autorelease没有影响。你可以释放他们,但他们永远不会释放。所以,他们是等于不是因为都是自动释放的字符串,但它们都是常量和释放被忽略。

The autorelease has no affect according to the doc ref above. You can release them but they are never deallocated. So, they are equal not because both are autoreleased string but that they're both constants and the release is ignored.

这篇关于NSString文字之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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