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!
-
Those aren't comparisons; they're assignments. So they wouldn't work even if that were actually the right way to check for nil.Chuck– Chuck2010-06-02 19:19:56 +00:00Commented Jun 2, 2010 at 19:19
-
Oops, thanks for catching that.John– John2010-06-02 19:28:17 +00:00Commented Jun 2, 2010 at 19:28
Add a comment
|
2 Answers
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:.)
3 Comments
pxl
is there any reason to go one step further with: if (str===NULL)?
kevingessner
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.dreamlax
@pxi: It is more idiomatic in Objective-C to compare objects to
nil rather than NULL. They boil down to the same thing though.