在 ObjectC 中初始化空字符串? [英] Initialize the empty string in ObjectC?
问题描述
有人用下面的来初始化NSstring
Someone use the following to initialize the NSstring
NSString *astring = [[NSString alloc] init];
我想知道为什么不直接使用
I am wondering why not just use
NSString *atring = nil or NSString *astring = @""
推荐答案
NSString *astring = [[NSString alloc] init];
和语义没有区别NSString *astring = @"";
- 但 NSString *astring = nil;
是完全不同的.前两个产生对不可变字符串值的引用,最后一个表示不存在一个值.
There is no semantic difference between NSString *astring = [[NSString alloc] init];
and NSString *astring = @"";
- but NSString *astring = nil;
is completely different. The first two produce a reference to an immutable string value, the last indicates the absence of a value.
生成零长度字符串的各种方式是否产生不同的对象完全是一个实现细节.代码:
Whether the various ways of generating an zero-length string produce different objects is entirely an implementation detail. The code:
NSString *a = [[NSString alloc] init];
NSString *b = [NSString new];
NSString *c = @"";
NSString *d = [NSString stringWithString:@""];
NSLog(@"%p, %p, %p, %p, %p", a, b, c, d, @""); // %p = print the value of the reference itself
输出(确切值会有所不同):
outputs (the exact values will vary):
0x7fff7100c190, 0x7fff7100c190, 0x1000028d0, 0x1000028d0, 0x1000028d0
显示仅创建了 2 个零长度字符串对象 - 一个用于 @""
,另一个用于 alloc
/init
.由于字符串是不可变的,这样的共享是安全的,但通常您应该不要依赖它并尝试使用引用比较(==
).
showing only 2 zero-length string objects were created - one for @""
and one for alloc
/init
. As the strings are immutable such sharing is safe, but in general you should not rely on it and try to compare strings using reference comparison (==
).
这篇关于在 ObjectC 中初始化空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!