简体   繁体   English

在ObjectC中初始化空字符串?

[英]Initialize the empty string in ObjectC?

Someone use the following to initialize the NSstring 有人使用以下内容初始化NSstring

NSString *astring = [[NSString alloc] init];

I am wondering why not just use 我想知道为什么不使用

NSString *atring = nil or NSString *astring = @""

There is no semantic difference between NSString *astring = [[NSString alloc] init]; NSString *astring = [[NSString alloc] init];之间没有语义差异NSString *astring = [[NSString alloc] init]; and NSString *astring = @""; NSString *astring = @""; - but NSString *astring = nil; - 但是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

showing only 2 zero-length string objects were created - one for @"" and one for alloc / init . 仅显示2个零长度字符串对象 - 一个用于@"" ,另一个用于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 ( == ). 由于字符串是不可变的这种共享是安全的,但一般而言,您应该依赖于它,并尝试使用比较基准比较(字符串== )。

NSString *atring = nil

is different -- it's a nil pointer, not an empty string. 是不同的 - 它是一个零指针,而不是一个空字符串。

NSString *astring = @""

is almost the same, if you change it to something like 几乎是一样的,如果你把它改成类似的东西

NSString* astring=[@"" retain];

It's one of the things that "don't matter"; 这是“无关紧要”的事情之一; he or she simply used one way. 他或她只是单向使用。 Probably for no particular reason at all. 可能完全没有特别的理由。

NSString *atring = nil; NSString * atring = nil; is simply setting the pointer to nil and does nothing other than ensure that pointer is set to nil; 只是将指针设置为nil,除了确保指针设置为nil之外什么都不做;

NSString *astring = @""; NSString * astring = @“”; is a shorthand literal and is the equivalent of [NSString stringWithString:@""]; 是一个简写文字,相当于[NSString stringWithString:@“”];

On another point I don't know why you would want to initialize a string to nothing if its not mutable since you won't be able to change it later without overriding it. 另一方面,我不知道为什么你想要将一个字符串初始化为零,如果它不可变,因为你以后不能更改它而不会覆盖它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM