user2724095
user2724095

Reputation: 1

NSString object compare nil

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

Answers (1)

Peter Hosey
Peter Hosey

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”?

Testing whether it's nil

The documentation for the isEqual: method says:

  • anObject: The object to be compared to the receiver. May be nil, in which case this method returns NO.

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:

  • If XMLOut is nil, the answer is always NO no matter the question.
  • If 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.

Testing whether it's empty

As mah already told you in their comment, ask the string for its length.

  • If XMLOut is nil, the answer is always zero no matter the question.
  • If XMLOut is an empty string, its length is zero.
  • If XMLOut is any other string, its length is greater than zero.

Upvotes: 1

Related Questions