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

- by

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!

If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site witout any pesky ads! More details here.

Add your voice!

This site uses Akismet to reduce spam. Learn how your comment data is processed.