Search code examples
objective-ccocoa-touchuipickerview

What is an adequate test for (null)?


In my code I am using this test to check that the user has selected something in a pickerView:

if ( !selection || [selection isEqualToString:@"Select..."] ) {}

However, many posts on Stack Overflow recommend either using NSNull or a test like this example below:

if ( selection.length == 0 || [selection isEqualToString:@"(null)"] ) {}

There are also a number of variations of the above line of code all testing for a null where I am just using: !selection

Is my test incomplete and open to bugs creeping in? What is the difference between the !selection and these other tests?


Solution

  • The only bug I can foresee is a localization bug. What if you are setting the picker data somewhere using NSLocalizedString(), and forgot to properly check the @"Select..." according to the current localization? That would be very annoying, especially if your testers don't thoroughly test all localizations...

    However, !selection and selection.length == 0 should both be OK, even though selection would be nil, and nil.length won't make sense... So, I'd say go with:

    if ( !selection || [selection isEqualToString:@"(null)"] ) {}