1

I want to detect whether passing a NSString to NSLog will return (null). I've tried if (string == @"") {do something}" and if (string == @"(null)") {do something}" but neither seem to work. Any advice would be greatly appreciated!

2
  • Those aren't comparisons; they're assignments. So they wouldn't work even if that were actually the right way to check for nil. Commented Jun 2, 2010 at 19:19
  • Oops, thanks for catching that. Commented Jun 2, 2010 at 19:28

2 Answers 2

9

Your "NSString" is actually a pointer to an NSString (i.e. an NSString *). A null pointer in C is simply a pointer with the value 0; in C, 0 is false, so the following is simple and idiomatic:

NSString *str = ...;
if (str) {
    /// str is not null
}

(p.s.: Your comparisons with @"" and @"(null)" are comparing the addresses of the NSString pointers, not the values; to compare NSStrings, look at -isEqualToString:.)

Sign up to request clarification or add additional context in comments.

3 Comments

is there any reason to go one step further with: if (str===NULL)?
Well, C (and thus Objective-C) doesn't have a === operator, but you're free to use == or any other boolean operator. It's just not necessary, in the same way that writing if (some_bool == YES) is the same as if (some_bool), just with more characters.
@pxi: It is more idiomatic in Objective-C to compare objects to nil rather than NULL. They boil down to the same thing though.
6
if (string == nil) {
   do_something;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.