'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 1:[1]

The strict equality operator (===) exists in JS because the regular equality operator (==) does an implicit type conversion if you are comparing two different data types. One of the arguments will be converted to match with the other based on a set of unintuitive rules. For example, 1 == TRUE will give you 'true' even though 1 is a number and TRUE is a boolean. Does anybody know if Objective-C does implicit type conversions like this?

Solution 2:[2]

AFAIK there is no equivalent to === in Objective-C.

You can compare int with float using ==, which is not a good idea for other reasons. When you compare two ids (eg. UIView* and UIButton*) with == then you compare the pointer values. If that is TRUE/YES then it is an identical, not even just equal, object. It is the same instance.

When comparing objects for equality of their values then you are far better of by using the isEqual: method. You may have to overwrite isEqual in your own subclasses in order to use it properly with your own object.

If you had some concrete problem/excample then we could explain it better, I think.

Solution 3:[3]

Operator like === do not exist in Objective C.

And basically there is one general rule if you want to compare two objects: Use isEqual: and don't use == for objects. Unless you are pretty sure, what you are doing.

Here quite good link to get in depth knowledge: ObjectComparison

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 stefvhuynh
Solution 2 Hermann Klecker
Solution 3 JeremyP