Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize the empty string in ObjectC?

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 = @""
like image 234
user496949 Avatar asked Dec 04 '22 03:12

user496949


1 Answers

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 (==).

like image 61
CRD Avatar answered Dec 25 '22 20:12

CRD