How to test for a (null) string in Objective C

I wanted to test if a string has a value when it’s returned from Core Data. So I thought, the right way to do this was to see if it’s equal to nothing, like so:

if ([myString isEqualToString:@""]) {
    // should be empty... but may not be

But to my surprise this didn’t work – because my string was (null) rather than “empty” or nil, which in Objective C are not the same thing.

Instead we can test for the length of this string, and if it returns zero, then we’re sure it’s empty:

    if ([myString length] == 0) {
        // definitely empty!

Leave a Reply