I have a NSString
object,
NSString *aString;
then are the two following versions equivalent?
Version 1 :
if ( (NSString *)[NSNull null] == aString )
{
// Logic handling
}
Version 2 :
if ( nil == aString )
{
// Logic handling
}
Reference Posts
Update - Test Result
My simple test result shows that the above two versions have different behaviors:
When
aString
is initialized and then assigned withnil
:false
for expression in version 1,true
for expression in version 2.When
aString
is initialized with the value of@""
.false
for expression in version 1,false
for expression in version 2.
So it's clear that the two versions are not equivalent in their behavior.
The test 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 Do I Mean "Empty string"**
Now I've made it clearer that it's different for a NSString
object to be nil
and for it to be a valid initialized instance holding an empty string value of @""
. What I really need in this post is that how to test if my NSString
object is successfully initialized, that is, if aString
is nil
. I want to know if there is any difference for the above two versions of test code.
if ( aString == (NSString *)[NSNull null] )
withif ( aString == nil )
? – Tindall@""
. – Tindallif ( aString == nil )
byif (!aString)
– NippleaString.length == 0
– Lucia[aString length]
also yields0
even ifaString
fails to get initialized? For example, by this initialization code:NSString *aString = [aNSMutableDictionaryVariable objectForKey:@"stringKey"];
and right after this initialization, there goes the check codeaString
withif (0 == [aString length]){}
– TindallaString == nil
is wrong but!aString
is correct? Or do you mean they're equivalent, but the latter is better since it's simpler? – TindallNSDictionary
to convertNSNull
tonil
automatically. – Lucia