Reputation: 1
so I have NSString object that I declare so :
NSString *XMLOut;
Now this object can be empty or non empty.
How can I see it ?
If ([XMLOut isEqual:nil]) {
NSLog(@"XMLOut is empty");
} else {
NSLog(@"XMLOut is not empty");
}
is it correct ?
Upvotes: 0
Views: 95
Reputation: 96323
Now this object can be empty or non empty.
Empty is not the same thing as nil
.
An empty string is still a string. It has a length
(zero), you can append other strings to it, include it in strings to be joined by some character, etc.
nil
is no object. There is no string there. There is nothing there. It has no length, nor any other properties.
So, do you mean “I want to compare my string, which may be nil
, to determine whether it is nil
”, or “I want to compare my string, which may be empty, to determine whether it is empty”?
nil
The documentation for the isEqual:
method says:
anObject
: The object to be compared to the receiver. May benil
, in which case this method returnsNO
.
So, if XMLOut
is not nil
, [XMLOut isEqual:nil]
is guaranteed to return NO
.
But what if it's not nil
?
Messages to nil
return basically every kind of zero (excepting structures and the like), which includes NO
.
Which means that [XMLOut isEqual:nil]
will always be NO
:
XMLOut
is nil
, the answer is always NO
no matter the question.XMLOut
is not nil
, the answer is NO
because no string is equal to nil
.Use the ==
operator instead. XMLOut == nil
will correctly test whether XMLOut
is nil
.
As mah already told you in their comment, ask the string for its length
.
XMLOut
is nil
, the answer is always zero no matter the question.XMLOut
is an empty string, its length is zero.XMLOut
is any other string, its length is greater than zero.Upvotes: 1