Why the String length is 6?

133 Views Asked by At
NSString *str = nil;
NSLog(@"str = %@",str);
NSLog(@"str.length = %u",str.length);

NSString *str2 = [NSString stringWithFormat:@"%@",str];
NSLog(@"str2 = %@",str2);
NSLog(@"str2.length = %u",str2.length);

The NSLog imformations are:

str = (null)
str.length = 0
str2 = (null)
str2.length = 6

str2.length= 6 make me confused,why?

1

There are 1 best solutions below

0
Sergey Kalinichenko On

This looks confusing indeed. The reason for this, however, is simple: when you call [NSString stringWithFormat:@"%@", str]; and pass nil for str, you get a string that spells literally

"(null)"

Quotes are for clarity, they are not part of the string. As you can see, the string has exactly six characters.