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 = @""
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
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 (==
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With