views:

115

answers:

2

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!

+5  A: 
if (string == nil) {
   do_something;
}
Elfred
+9  A: 

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:.)

kevingessner
is there any reason to go one step further with: if (str===NULL)?
pxl
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.
kevingessner
@pxi: It is more idiomatic in Objective-C to compare objects to `nil` rather than `NULL`. They boil down to the same thing though.
dreamlax