I have an NSString object,
NSString *aString;
that is, the next two versions are equivalent?
Version 1:
if ( (NSString *)[NSNull null] == aString ) {
Version 2:
if ( nil == aString ) {
Help Messages
The difference between nil, nil and null
How to determine if NSString is null?
Apple NSNull Reference
How to check if a string is empty in Objective-C?
Update - test result
My simple test result shows that these two versions have different types of behavior:
When aString initialized and then assigned with nil :
false for expression in version 1,
true for expression in version 2.
When aString initialized to @"" .
false for expression in version 1,
false for expression in version 2.
So, it is clear that these two versions are not equivalent in their behavior.
Security Code:
NSString *aString = nil; NSString *bString = [NSString stringWithFormat:@""]; if ((NSString *)[NSNull null] == aString) { NSLog(@"a1 - true"); } else { NSLog(@"a1 - false"); } if (nil == aString) { NSLog(@"a2 - true"); } else { NSLog(@"a2 - false"); } if ((NSString *)[NSNull null] == bString) { NSLog(@"b1 - true"); } else { NSLog(@"b1 - false"); } if (nil == bString) { NSLog(@"b2 - true"); } else { NSLog(@"b2 - false"); }
Console output:
2013-10-31 00:56:48.132 emptyproject[31104:70b] a1 - false 2013-10-31 00:56:48.133 emptyproject[31104:70b] a2 - true 2013-10-31 00:56:48.133 emptyproject[31104:70b] b1 - false 2013-10-31 00:56:48.133 emptyproject[31104:70b] b2 - false
Update - What I mean by "Empty String" **
Now I have made it clear that the NSString object will be nil , and it must be a valid initialized instance containing an empty string value @"" . What I really need in this post is how to check if my NSString object was successfully initialized, i.e. if aString is nil . I want to know if there is a difference for the two versions of the test code.
null objective-c nsstring nsnull
Cong
source share