De- Mystifying Apple’s Compiler and String Comparison.

So, turns out that many iOSDev’s are being fooled by what the following should return…

Comparing strings or Memory Address?

Objective C, ok we get it, it’s an Object Orientated programming language dating back some time now and many dev’s would instantly assume that ‘==’ would compare the memory address’ of the 2 strings, instantiated separately and well, they are correct.

So wait hold on, (Thanks @nanasarpong)

How… but… did it…thats not… but it…

See, when you create strings in the literal sense in Objective C, the Compiler, GCC/Clang et al will optimize what it knows are identical string constants and give them the same memory address. Oh what a perfect world we live in.

So thats the long and short of it, that said, if I ever performed a code review on anyone comparing strings in this sense then god help me.

You should, and always, use ‘isEqualToString’

You can get away with ‘isEqual:’ but there is argument that ‘isEqualToString’ executes faster, but I haven't done my homework.

Anyway, another hot- shot question tomorrow maybe..

Thanks

TheiOSDude.com

Senior iOS Engineer  — Advanced Github downloader — Serial StackOverflow browser

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store