Search code examples
objective-cequality

Objective C: equality == and strict equality ===


As a Javascript programmer it has been drummed into my head to use === instead of == where ever possible.

As I'm learning Objective C, even in the official documentation, I only ever see == being used.

My question is, should I continue my habits of using strict equality in my Objective C code? Is it as necessary as it is with Javascript? I would assume strict equality gives a slight performance boost, but in Objective C is this boost too slight to make much of a difference?


Solution

  • It's very simple, in Objective C, you don't have the === operator.

    You usually don't use == to compare objects, because it compares the pointer values, not the value of the objects. So, if you want to compare two strings for example, you should use:

    [stringObject isEqual:@"the string"];
    

    This compares the string value, not the pointers. There are however valid reasons to use the == operator to compare objects. Many delegate callbacks have the sender object as a parameter. If you are implementing multiple tableviews with one controller, for instance, you want to check which tableview is calling your method:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
      if (tableView == self.firstTableView) {
         ...
      }
    
       if (tableView == self.secondTableView) {
         ...
      }
    ...
    }