Archive for January, 2010

Always use isEqualToString for string comparisons

While working on my iPhone app Quickie, I encountered one of many examples why you must always check your code on the actual device.

Quickie uses Core Data for storage and in one particular place I was comparing the NSString variable to a NSString–typed property of my CoreData class, QuickieList. Like this:

OBJC:
  1. if (QuickieList.listName != theListName)

listName is defined as NSString and theListName is obviously that as well. In this particular instance, both of those had the value of “test”.
In the iPhone Simulator (running on 10.6.2) this comparison returned false, but on the iPhone running 3.1.2 it returned true. When changed into:

OBJC:
  1. if (![QuickieList.listName isEqualToString:theListName])

result was the same.

Never – I repeat — never assume that simulator testing will be fine, even for seemingly small things. It can bite you when you least expect it.

UITextField.text is not always there

If you have UITextField on the page and you need to validate is there something in it (so if yes you can save the input or something), you might do something like this:

OBJC:
  1. if (![addNewCellTextField.text isEqualToString:@""]) {
  2. }

However, this will fail if the field is never touched. That is, until your user taps the field and it gets focus, UITextField.text is nil. Which means that condition above yields true, which is not what you want.
Once it is touched though, this becomes an instance of NSString with value of @””. Thus, always use:

OBJC:
  1. if (addNewCellTextField.text != nil && ![addNewCellTextField.text isEqualToString:@""]) {
  2. }

Watch out for this little trap hole.